主页有其他数据结构内容(持续更新中)
难度:Medium
代码:
法一:dfs
class Solution {
private:
int direction[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; // 分别代表右、下、左、上四个方向
void dfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y) {
// 对当前位置的上下左右进行dfs
for(int k = 0; k < 4; k++) {
int nextX = x + direction[k][0];
int nextY = y + direction[k][1];
if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) {
// 越界
continue;
}
if(!visited[nextX][nextY] && grid[nextX][nextY] == '1') {
visited[nextX][nextY] = true;
dfs(grid, visited, nextX, nextY);
}
}
}
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(); // 行数
int n = grid[0].size(); // 列数
vector<vector<bool>> visited(m, vector<bool>(n, false));
int count = 0; // 计数器
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(!visited[i][j] && grid[i][j] == '1') {
// 如果当前位置是一块未访问过的陆地,就将其进行标记,并令count++,接着对当前节点进行dfs
visited[i][j] = true;
count++;
dfs(grid, visited, i, j);
}
}
}
return count;
}
};
法二:bfs
class Solution {
private:
int direction[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
void bfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y) {
queue<pair<int, int>> q;
q.push({x, y});
// 只要加入队列,立刻标记
visited[x][y] = true;
while(!q.empty()) {
pair<int, int> cur = q.front();
q.pop();
for(int k = 0; k < 4; k++) {
int nextX = cur.first + direction[k][0];
int nextY = cur.second + direction[k][1];
if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) {
continue;
}
if(!visited[nextX][nextY] && grid[nextX][nextY] == '1') {
q.push({nextX, nextY});
// 只要加入队列,立刻标记
visited[nextX][nextY] = true;
}
}
}
}
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
int count = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(!visited[i][j] && grid[i][j] == '1') {
count++;
bfs(grid, visited, i, j);
}
}
}
return count;
}
};