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
用DFS,遇到1就ans++,然后搜索所有他的1邻居直到搜不到了,这时代表有一个island,
接下来继续搜索,原理同上
class Solution { public int numIslands(char[][] grid) { int m = grid.length; if(m == 0) return 0; int n = grid[0].length; int ans = 0; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if (grid[i][j]=='1'){ ans++; DFS(grid,m,n,i,j); } } } return ans; } private void DFS(char[][] grid, int m, int n, int i, int j){ if(i < 0|| j < 0|| i >= m || j >=n|| grid[i][j] == '0') return; grid[i][j] = '0'; DFS(grid,m,n,i+1,j); DFS(grid,m,n,i-1,j); DFS(grid,m,n,i,j+1); DFS(grid,m,n,i,j-1); } }
ref:https://www.youtube.com/watch?v=XSmgFKe-XYU
总结:
This is a dfs question asked us to calculate the number of islands, which is denoted by all consecutive '1' s.
So we can itereate char array, when it meets a '1', we go into dfs process, which is to set all current island's '1' to 0. That's why we don't worry about if this cell already used or not.
Then we dfs to its 4 directions.