最近回了一趟家,看了看父母,感觉金钱与亲情相比,金钱还是差远了,正所谓“万恶淫为首,百善孝为先”。言归正传,刚刚刷了一道题,下面就和大家分享一下经验吧!
题目如下:
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(表示陆地)和0(表示水域)的二维平面,请计算岛屿的数目。其中岛屿是指被水域环绕的陆地。
方法一(DFS递归法)
与“https://blog.csdn.net/Vensmallzeng/article/details/96983286”的方法一思路大体一致,不同之处在于,① 本题的递归函数中没有递归终止条件,只将满足条件的‘1’字符标记成false就行,并且在后续中不用清除此标记;② 需要用一个变量res记录岛屿的个数。
解题代码如下:
class Solution{
private:
vector<vector<bool>> visited;
int d[4][2] = { {-1,0},{0,-1},{1,0},{0,1} };
int row;
int col;
void findnumIslands( vector<vector<char>>& grid, int startx, int starty ){
visited[startx][starty] = true;
for( int i = 0; i < 4; i ++ ) {
int newx = startx + d[i][0];
int newy = starty + d[i][1];
if (newx >= 0 && newx < row && newy >= 0 && newy < col && !visited[newx][newy] && grid[newx][newy] == '1')
findnumIslands( grid, newx, newy );
}
}
public:
int numIslands(vector<vector<char>> & grid){
row = grid.size();
if ( row == 0 ) return 0;
col = grid[0].size();
int res = 0;
visited = vector<vector<bool>>( row, vector<bool>(col, false) );
for (int i = 0; i < row; i ++) {
for (int j = 0; j < col; j ++) {
if( grid[i][j] == '1' && !visited[i][j] ){
res ++;
findnumIslands( grid, i, j );
}
}
}
return res;
}
};
提交后的结果如下:
方法二(优化方法一)
这里可以不用创建bool型的visited数组,访问过的‘1’字符直接置为'#'即可。
解题代码如下:
class Solution{
private:
int d[4][2] = { {-1,0},{0,-1},{1,0},{0,1} };
int row;
int col;
void findnumIslands( vector<vector<char>>& grid, int startx, int starty ){
grid[startx][starty] = '#';
for( int i = 0; i < 4; i ++ ) {
int newx = startx + d[i][0];
int newy = starty + d[i][1];
if (newx >= 0 && newx < row && newy >= 0 && newy < col && grid[newx][newy] == '1')
findnumIslands( grid, newx, newy );
}
return;
}
public:
int numIslands(vector<vector<char>> & grid){
row = grid.size();
if ( row == 0 ) return 0;
col = grid[0].size();
int res = 0;
for (int i = 0; i < row; i ++) {
for (int j = 0; j < col; j ++) {
if( grid[i][j] == '1'){
res ++;
findnumIslands( grid, i, j );
}
}
}
return res;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。