题目描述:
给定一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入: 11110 11010 11000 00000 输出: 1
示例 2:
输入: 11000 11000 00100 00011 输出: 3
思路:这道题我的思路是遍历整个矩阵,用一个辅助矩阵来记录轨迹,已经走过的地方不在重复访问,一直遍历到周围全是0的节点返回。具体的代码如下:
class Solution {
public:
void numIslandsCore(vector<vector<char>>& grid, int &height, int &width, int x, int y, vector<vector<int>>& visited){
if(visited[x][y] == 1) return;
visited[x][y] = 1;
if(grid[x][y] == '0') return;
if(x+1<height && grid[x+1][y] == '1') numIslandsCore(grid, height, width, x+1, y, visited);//下移
if(x-1>=0 && grid[x-1][y] == '1') numIslandsCore(grid, height, width, x-1, y, visited);//上移
if(y-1>=0 && grid[x][y-1] == '1') numIslandsCore(grid, height, width, x, y-1, visited);//左移
if(y+1<width && grid[x][y+1] == '1') numIslandsCore(grid, height, width, x, y+1, visited);//右移
}
int numIslands(vector<vector<char>>& grid) {
if(0 == grid.size()) return 0;
int isLandNums = 0, height = grid.size(), width = grid[0].size();
vector<vector<int>> visited(height, vector<int>(width, 0));
for(int start_x = 0; start_x < height; ++start_x){
for(int start_y = 0; start_y < width; ++start_y){
//如果遇到的是没有被访问过的为1的点,从该点遍历,一定可以得到一个岛屿
if(visited[start_x][start_y] == 0 && grid[start_x][start_y] == '1'){
isLandNums++;
numIslandsCore(grid, height, width, start_x, start_y, visited);
}
else continue;
}
}
return isLandNums;
}
};