题目链接:https://leetcode-cn.com/problems/number-of-islands/
求联通块个数有几种方法,
dfs方法:
class Solution {
private:
int n, m;
int dir[4][2] = { {0,1},{0,-1}, {1, 0}, {-1,0} };
public:
// dfs
void dfs(vector<vector<char>>& grid, int r, int c) {
grid[r][c] = '0';
int nr, nc;
for(int i = 0; i < 4; i++) {
nr = r + dir[i][0];
nc = c + dir[i][1];
if(nc >= 0 && nr >= 0 && nc < m && nr < n && grid[nr][nc] == '1') dfs(grid, nr, nc);
}
}
int numIslands(vector<vector<char>>& grid) {
n = grid.size();
m = grid[0].size();
int ret = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == '1') {
ret++;
dfs(grid, i, j);
}
}
}
return ret;
}
};
BFS方法
class Solution {
private:
int n, m;
int dir[4][2] = {{0,1},{0,-1},{1, 0},{-1,0}};
public:
// bfs
int numIslands(vector<vector<char>>& grid) {
n = grid.size();
m = grid[0].size();
queue<pair<int, int> > qu;
int ret = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if( grid[i][j] == '1' ) {
qu.push({i, j});
ret++;
grid[i][j] = '0';
while(!qu.empty()) {
auto tmp = qu.front();
qu.pop();
int r = tmp.first;
int c = tmp.second;
// grid[nr][nc] = '0'; 注:一开始在这里清0,然后超时了,因为会多次重复加入到队列中
for(int k = 0; k < 4; k++) {
int nr = r + dir[k][0];
int nc = c + dir[k][1];
if(nr >= 0&&nc >=0 && nr < n && nc < m && grid[nr][nc] == '1') {
qu.push({nr, nc}); grid[nr][nc] = '0';
}
}
}
}
}
}
return ret;
}
};
并查集方法
class Solution {
private:
int n, m;
int dir[4][2] = {{0,1},{0,-1},{1, 0},{-1,0}};
vector<int> parent;
int cnt;
public:
// 并查集
int F(int x) { return x == parent[x] ? x : parent[x] = F(parent[x]); }
void U(int x, int y) {
int fx = F(x);
int fy = F(y);
if(fx != fy) {
parent[fx] = fy;
cnt++;
}
}
inline int get_idx(int r, int c) {
return r * m + c;
}
int numIslands(vector<vector<char>>& grid) {
n = grid.size();
m = grid[0].size();
// init
parent.resize(n*m);
for(int i = 0; i < n*m; i++) {
parent[i] = i;
}
cnt = 0;
/**/
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == '1') {
for(int k = 0; k < 4;k++) {
int nr = i + dir[k][0];
int nc = j + dir[k][1];
if(nr >= 0 && nc >= 0 && nr <= n && nc <= m && grid[nr][nc] == '1') {
U(get_idx(i,j), get_idx(nr, nc));
}
}
}
else cnt++;
}
}
return n * m - cnt;
}
};