思路1: bfs 时间复杂度O(m*n)
class Solution {
public:
int xy[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int flag[305][305];
void bfs(vector<vector<char>>& grid, int x, int y) {
int n = grid.size(), m = grid[0].size();
queue<pair<int, int>> q;
q.push({x, y});
flag[x][y] = true;
while (!q.empty()) {
auto frt = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int xx = frt.first + xy[i][0];
int yy = frt.second + xy[i][1];
if (xx < 0 || xx > n - 1 || yy < 0 || yy > m - 1) continue;
if (grid[xx][yy] == '1' && !flag[xx][yy]) {
q.push({xx, yy});
flag[xx][yy] = true;
}
}
}
}
int numIslands(vector<vector<char>>& grid) {
int n = grid.size(), m = grid[0].size(), ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == '1' && !flag[i][j]) {
ans++;
bfs(grid, i, j);
}
}
}
return ans;
}
};
思路2: dfs 时间复杂度O(m*n)
void dfs(vector<vector<char>>& grid, int x, int y) {
int n = grid.size(), m = grid[0].size();
flag[x][y] = 1;
for (int i = 0; i < 4; ++i) {
int xx = x + xy[i][0];
int yy = y + xy[i][1];
if (xx < 0 || xx > n - 1 || yy < 0 || yy > m - 1) continue;
if (grid[xx][yy] == '1' && !flag[xx][yy]) {
dfs(grid, xx, yy);
}
}
}
思路3: 并查集 时间复杂度O(m*n)
class Solution {
public:
vector<int> father;
void unite (int u, int v) {
int fau = findfather(u);
int fav = findfather(v);
if (fau != fav) father[fau] = fav;
}
int findfather(int m) {
if (father[m] == m) return m;
return father[m] = findfather(father[m]);
}
int numIslands(vector<vector<char>>& grid) {
int n = grid.size(), m = grid[0].size(), ans = 0;
father.resize(m * n);
for (int i = 0; i < m * n; ++i) {
father[i] = i;
}
auto getindex = [&](int x, int y) {
return x * m + y;
};
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == '1') {
if (i - 1 >= 0 && grid[i - 1][j] == '1')
unite(getindex(i - 1, j), getindex(i, j));
if (j - 1 >= 0 && grid[i][j - 1] == '1')
unite(getindex(i, j - 1), getindex(i, j));
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == '1' && father[getindex(i, j)] == getindex(i, j)) {
ans++;
}
}
}
return ans;
}
};