简单的dfs递归,我们把每个访问到的‘1’,都对其进行dfs,使得与他相邻的‘1’都置为‘0’
/**
* @author johnsondu
* @problem Number of Islands
* @url https://leetcode.com/problems/number-of-islands/
* @timeComlexity O(n^2)
* @spaceComplexity O(1)
* @strategy See code.
*/
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
class Solution {
public:
void dfs(int x, int y, int row, int col, vector<vector<char>>& grid)
{
for(int i = 0; i < 4; i ++) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < row && tx >= 0 && ty < col && ty >= 0) {
if(grid[tx][ty] == '1') {
grid[tx][ty] = '0';
dfs(tx, ty, row, col, grid);
}
}
}
}
int numIslands(vector<vector<char>>& grid) {
int row = grid.size();
if(row == 0) return 0;
int col = grid[0].size();
if(col == 0) return 0;
int cnt = 0;
for(int i = 0; i < row; i ++)
for(int j = 0; j < col; j ++) {
if(grid[i][j] == '1') {
cnt ++;
dfs(i, j, row, col, grid);
}
}
return cnt;
}
};
本文介绍了一种使用深度优先搜索(DFS)算法解决岛屿数量问题的方法。通过递归地访问地图上的每个单元格,将相连的陆地标记并计数,最终得出不相连陆地块的数量。此算法的时间复杂度为O(n^2),空间复杂度为O(1)。

717

被折叠的 条评论
为什么被折叠?



