Golang Leetcode 200. Number of Islands.go

2019-04-12 11:25:31 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412908

思路

dfs,深度优先搜索

首先找到一个等于1的节点

然后递归的去看周围四个方向的节点是不是也是1

code

代码语言:javascript复制
func numIslands(grid [][]byte) int {
	if len(grid) == 0 {
		return 0
	}
	ret := 0
	for i := 0; i < len(grid); i   {
		for j := 0; j < len(grid[0]); j   {
			if grid[i][j] == '1' {
				helper(grid, i, j)
				ret  
			}
		}
	}
	return ret
}

func helper(grid [][]byte, i, j int) {
	if i < 0 || j < 0 || i >= len(grid) || j >= len(grid[0]) {
		return
	}
	if grid[i][j] == '1' {
		grid[i][j] = '0'
		helper(grid, i-1, j)
		helper(grid, i, j-1)
		helper(grid, i 1, j)
		helper(grid, i, j 1)
	}
}

0 人点赞