# DFS&BFS - 200. Number of Islands

200. Number of Islands

Given a 2d grid map of `'1'`s (land) and `'0'`s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

``````Input:
11110
11010
11000
00000

Output: 1

``````

Example 2:

``````Input:
11000
11000
00100
00011

Output: 3
``````

go：

``````var dirs = [][]int{{-1, 0},{1, 0}, {0, -1}, {0, 1}}

func numIslands(grid [][]byte) int {
var res int
//sanity check
if grid == nil || len(grid) == 0 || len(grid[0]) == 0 {
return res
}

row, col := len(grid), len(grid[0])
for i := 0; i < row; i++ {
for j := 0; j < col; j++ {
if grid[i][j] == '1' {
res++
dfs(&grid, i, j, row, col)
}
}
}

return res
}

func dfs(grid *[][]byte, x, y int, row, col int) {
// base case
if x < 0 || x >= row || y < 0 || y >= col || (*grid)[x][y] == '0' || (*grid)[x][y] == '2' {
return
}

(*grid)[x][y] = '2'
for _, dir := range dirs {
dfs(grid, dir[0] + x, dir[1] + y, row, col)
}
}
``````

Nothing just happens, it's all part of a plan.