Leetcode Number of islands

这题复用了word serach的很多代码 , 还把问题降级到找出从某个点开始能floodfill到的格子数 , 一次过了

findCloseGrids(grid,srow,scol) {
    if grid[srow][scol]!=1 {
        return 0
    }

    res=1
    mark [srow,scol] as visited

    access in up down right left order
        if [nrow,ncol] not visited and inarea
            res+=findCloseGrids(grid,nrow,ncol)

    return res
}
type Solution struct {
    visited map[int]map[int]bool
}

func (t *Solution) findCloseGrids(grid [][]byte , srow int,scol int) int {
    if grid[srow][scol]!='1' {
        return 0
    }

    res:=1
    if _,ok:=t.visited[srow];!ok {
        t.visited[srow] = make(map[int]bool)
    }
    t.visited[srow][scol] = true

    coord := [][]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} //up right down  left

    for _, v := range coord {
        nrow := srow + v[0]
        ncol := scol + v[1]
        if inArea(ncol, nrow, grid) && !t._visited(ncol, nrow) {
            res += t.findCloseGrids(grid,nrow,ncol)
        }
    }
    return res
}

func (t *Solution) _visited(col int, row int) bool {
    if _, ok := t.visited[row][col]; ok {
        return true

    } else {
        return false
    }
}

func inArea(col int, row int, board [][]byte) bool {
    return row >= 0 && row <= len(board)-1 && col >= 0 && col <= len(board[0])-1
}

func numIslands(grid [][]byte) int {
    s := Solution{visited: make(map[int]map[int]bool)}
    res:=0
    for row, rowdata := range grid {
        for col, _ := range rowdata {
            if !s._visited(col,row) {
                if  s.findCloseGrids(grid,row,col)>0{
                    res+=1
                }
            }
        }
    }
    return res
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!