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:
11110 11010 11000 00000Answer: 1
Example 2:
11000 11000 00100 00011Answer: 3
Credits: Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
本题的关键在于,每找到一个‘1’,就应该dfs,将其周边的‘1’,全部置成其他值,甚至可以是‘0’,这样保证下一次找到‘1’时,是一个全新的‘1’。
代码
class Solution { public: void dfs(vector<vector<char>>& grid,int i, int j) { if(i<0||j<0||i>=grid.size()||j>=grid[0].size()) { return; } else { if(grid[i][j]=='1') { grid[i][j]='2'; dfs(grid,i-1,j); dfs(grid,i,j-1); dfs(grid,i+1,j); dfs(grid,i,j+1); } return ; } } int numIslands(vector<vector<char>>& grid) { if(grid.size()==0) return 0; int count=0; for(int i=0;i<grid.size();++i) for(int j=0;j<grid[0].size();++j) { if(grid[i][j]=='1') { count++; dfs(grid,i,j); } } return count; } };