【LeetCode】200. 岛屿数量
题目
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。
思路
代码
时间复杂度:O(row * col)
空间复杂度:O(row * col)
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty()) return 0;
int res = 0, row = grid.size(), col = grid[0].size();
vector<vector<bool>> visited(row, vector<bool>(col));
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (grid[i][j] == '1' && visited[i][j] == false) {
dfs(grid, visited, i, j);
++res;
}
}
}
return res;
}
void dfs(vector<vector<char>> &grid, vector<vector<bool>> &visited, int i, int j) {
int row = grid.size(), col = grid[0].size();
if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] == '0' || visited[i][j] == true) return;
visited[i][j] = true;
dfs(grid, visited, i - 1, j);
dfs(grid, visited, i + 1, j);
dfs(grid, visited, i, j - 1);
dfs(grid, visited, i, j + 1);
}
};
优化空间复杂度
访问过就重置值为 0。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int row = grid.size(), col = grid[0].size(), c = 0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (grid[i][j] == '1') {
++c;
dfs(grid, i, j);
}
}
}
return c;
}
void dfs(vector<vector<char>>& grid, int row, int col) {
if (row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size() || grid[row][col] == '0') return;
grid[row][col] = '0';
dfs(grid, row - 1, col);
dfs(grid, row + 1, col);
dfs(grid, row, col - 1);
dfs(grid, row, col + 1);
}
};