原题: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
思路:本题是经典的简单图论问题,求岛的个数也即求图上的连通区间的个数。可采用深搜或者广搜。假设共有n个点,时间复杂度为o(n)。本题笔者采用深搜的递归和非递归两种解法。将遍历过的“1”被改为“0”,其实达到的效果就是遍历完一个岛后,“把遍历过的岛变成海洋”。这是因为在下一次找岛的时候,找海洋和找遍历过的岛都一样没用。
非递归解法:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int num_of_island=0;
vector<pair<int,int>> island;
//一个island的点的坐标的集合
int index[8]={-1,0,1,0,0,-1,0,1};
//index[8]表示的是点(x,y)水平和垂直方向四个点的坐标偏移量
for(int i=0;i<grid.size();i++)
for(int j=0;j<grid[i].size();j++)
if(grid[i][j]=='1'){
num_of_island++;
island.push_back(make_pair(i,j));
grid[i][j]='0';
while(island.size()>0){
int len=island.size();
int x=island[len-1].first,y=island[len-1].second;
island.erase(island.begin()+len-1);
for(int k=0;k<4;k++)
if((x+index[2*k]>=0)&&(x+index[2*k]<grid.size())&&(y+index[2*k+1]>=0)&&(y+index[2*k+1]<grid[i].size()))
if(grid[x+index[2*k]][y+index[2*k+1]]=='1'){
island.push_back(make_pair(x+index[2*k],y+index[2*k+1]));
grid[x+index[2*k]][y+index[2*k+1]]='0';
}
}
}
return num_of_island;
}
};
递归解法:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int num_of_island=0;
for(int i=0;i<grid.size();i++)
for(int j=0;j<grid[i].size();j++)
if(grid[i][j]=='1'){
num_of_island++;
grid[i][j]='0';
dfs(grid,i,j);
}
return num_of_island;
}
void dfs(vector<vector<char>>& grid,int x,int y){
if((x<0)||(y<0)||(x>=grid.size())||(y>=grid[0].size()))
return;
else if(grid[x][y]=='1'){
grid[x][y]='0';
dfs(grid,x-1,y);
dfs(grid,x+1,y);
dfs(grid,x,y-1);
dfs(grid,x,y+1);
}
return;
}
};
//注:引用和指针传递会改变值,简单的值传递不会改变值。本题即是引用传递,传的是地址,所以grid的值也跟着改变。