leetcode 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

开始想用vis来记录访问过的岛屿
发现超时
直接将岛屿所在点变为0(陆地)
即可跳过访问grid[x][y] 1->0

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
class Solution {
public:
int m,n;
int numIslands(vector<vector<char>>& grid) {
m=grid.size();
if(m==0) return 0;
n=grid[0].size();

//vector<vector<int> > vis(100,vector<int>(100,0)); 直接把访问过的1岛屿 标记为0 grid[x][y]=0
int cnt=0;

for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
{
if(grid[i][j]!='0'){
// cout<<i<<" "<<j<<endl;
dfs(grid,i,j);
cnt++;

}

}


}

return cnt;
}

void dfs(vector<vector<char> >&grid,int x,int y){//grid传的是引用

if(x<0||x>=m||y<0||y>=n) return;
if(grid[x][y]=='0') return;//grid[x][y]==0 错误的 字符'0'
//if(vis[x][y]) return;
grid[x][y]='0';
for(int i=0;i<4;i++){
int newx=x+dir[i][0];
int newy=y+dir[i][1];
dfs(grid,newx,newy);
}



}
};