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
遇到1 ,就dfs 吃掉他的邻居。
1 class Solution { 2 public: 3 int numIslands(vector<vector<char>>& grid) { 4 if(grid.size()==0) return 0; 5 int cnt =0; 6 for(int i =0;i<grid.size();i++) 7 for(int j = 0;j <grid[0].size();j++){ 8 cnt+=grid[i][j]-'0'; 9 dfs(grid,i,j); 10 } 11 return cnt; 12 } 13 void dfs(vector<vector<char>>& grid,int x,int y ){ 14 if(x>= grid.size()||y>=grid[0].size()||x<0||y<0||grid[x][y]=='0') return ; 15 grid[x][y] = '0'; 16 dfs( grid,x-1,y); 17 dfs( grid,x+1,y); 18 dfs( grid,x,y-1); 19 dfs( grid,x,y+1); 20 } 21 };
http://zxi.mytechroad.com/blog/searching/leetcode-200-number-of-islands/