题目:
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进行Dfs,Dfs过了以后就把它标记为0,这样全部走一遍就知道有多少个联通块了。
接下来就是代码实现了,这次的代码还是遇见了一点小问题,先贴出有问题的代码:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int islandNum=0;
int row=grid.size();
int column=grid[0].size();
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
{
if(grid[i][j]=='1')
{
Dfs(grid,i,j);
islandNum++;
}
}
return islandNum;
}
void Dfs(vector<vector<char>>& g,int r,int c)
{
if(g[r][c]=='0') return;
g[r][c]='0';
if(r<g.size()-1)
Dfs(g,r+1,c);
if(c<g[0].size()-1)
Dfs(g,r,c+1);
}
};
报的错误是:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int islandNum=;
if(grid.size()==) return ;
if(grid[].size()==) return ;
int row=grid.size();
int column=grid[].size();
for(int i=;i<row;i++)
for(int j=;j<column;j++)
{
if(grid[i][j]=='')
{
Dfs(grid,i,j);
islandNum++;
}
}
return islandNum;
}
void Dfs(vector<vector<char>>& g,int r,int c)
{
if(g[r][c]=='') return;
g[r][c]='';
if(r<g.size()-)
Dfs(g,r+,c);
if(c<g[].size()-)
Dfs(g,r,c+);
if(r>)
Dfs(g,r-,c);
if(c>)
Dfs(g,r,c-);
}
};