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(意思是,如果仅仅是斜角都为1,不是ajacent land). You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
思路:找到没有标志的1,表示找到了一个island,然后找它的连通图,把这个连通图里的1都设置标志。
class Solution { public: int numIslands(vector<vector<char>>& grid) { int hight = grid.size(); if(hight == 0) return 0; int width = grid[0].size(); int ret = 0; for(int i = 0; i < hight; i++){ for(int j = 0; j < width; j++){ if(grid[i][j]=='0') continue; //find a land, continue to find land at its side ret++; grid[i][j] = '0'; //set flag dfs(grid, i+1, j); dfs(grid, i, j+1); dfs(grid, i-1, j); dfs(grid, i, j-1); } } return ret; } void dfs(vector<vector<char>>& grid, int i, int j){ int hight = grid.size(); int width = grid[0].size(); if(i>=hight || j>= width || i<0 || j<0) return; if(grid[i][j]=='0') return; //find a land, continue to find land at its side grid[i][j] = '0'; //set flag dfs(grid, i+1, j); dfs(grid, i, j+1); dfs(grid, i-1, j); dfs(grid, i, j-1); } };