Q:
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
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
题意大致是,给你一个有1和0组成的二维字符数组,1代表陆地,0代表水。问被水包围的连通陆地区域的个数。
solution:
这道题思路和之前的那几道题基本一致,使用DFS,BFS,并查集均可以解决。
poj2386Lake Counting(DFS算法)
(LeetCode 130) Surrounded Regions(BFS)
(LeetCode 130)Surrounded Regions(并查集)
关于这道题的解法,上面的三个链接里都有详细的介绍,这里我贴上这道题的代码就行了啊。分别是DFS和并查集的代码
这道题这两个方法的时间消耗是一样的,但是不怎么理想,如果大家有改进的方法希望也能够告诉我,谢谢了
DFS使用递归,代码要简洁很多。
并查集:
class Solution {
public:
vector<int> UN;
int count=0;
int numIslands(vector<vector<char>>& grid) {
if(grid.size()==0||grid[0].size()==0)return 0;
int length = grid.size()*grid[0].size();
int width = grid[0].size();
UN = vector<int>(length,0);
for(int i=0;i<length;i++){
int x=i/width,y=i%width;
if(grid[x][y]=='1')count++;
UN[i]=i;
}
cout<<count<<endl;
for(int j=0;j<length;j++){
int x=j/width,y=j%width;
int down=x+1,right=y+1;
if(down<grid.size()&&grid[x][y]=='1'&&grid[down][y]=='1')
unionset(j,j+width);
if(right<grid[0].size()&&grid[x][y]=='1'&&grid[x][right]=='1')
unionset(j,j+1);
}
return count;
}
void unionset(int m,int n){
int rootM=find(m);
int rootN=find(n);
if(rootM==rootN)return;
UN[rootN]=rootM;
//cout<<rootM<<" "<<rootN<<endl;
count--;
}
int find(int p){
while(p!=UN[p]){
UN[p]=UN[UN[p]];
p=UN[p];
}
return p;
}
};
- 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
DFS递归:
class Solution {
public:
vector<vector<int>>visit;
int px[4]={-1,1,0,0};
int py[4]={0,0,-1,1};
int count=0;
int numIslands(vector<vector<char>>& grid) {
if(grid.size()==0||grid[0].size()==0)return 0;
visit = vector<vector<int>>(grid.size(),vector<int>(grid[0].size(),0));
for(int i=0;i<grid.size();i++)
for(int j=0;j<grid[0].size();j++){
if(grid[i][j]=='0'||visit[i][j]==1)continue;
count++;
dfs(grid,i,j);
};
return count;
}
void dfs(vector<vector<char>>& grid,int m,int n){
visit[m][n]=1;
for(int i=0;i<4;i++){
int x=m+px[i],y=n+py[i];
if((x<0)||(x>=grid.size())||(y<0)||(y>=grid[0].size()))continue;
if(visit[x][y]==1)continue;
if(grid[x][y]=='0')continue;
dfs(grid,x,y);
}
}
};