class Solution {
public:
int result=0;
vector<vector<int>> visited;
int numIslands(vector<vector<char>>& grid) {
int rows=grid.size(),cols=grid.at(0).size();
visited.resize(rows,vector<int>(cols));
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(grid[i][j]=='1'&&visited[i][j]==0){
result++;
dfs(grid,visited,i,j);
}
}
}
return result;
}
void dfs(vector<vector<char>>& grid,vector<vector<int>>& visited,int row,int col){
// 判断 base case
// 如果坐标 (row, col) 超出了网格范围,直接返回
if (!inArea(grid, row, col)) {
return;
}
if(grid[row][col]=='0'){//是否是岛屿
return;
}
if(visited[row][col]){//已经被访问过了
return;
}
visited[row][col]=1;//未访问过,标记为访问过
// 访问上、下、左、右四个相邻结点
dfs(grid,visited, row - 1, col);
dfs(grid,visited, row + 1, col);
dfs(grid,visited, row, col - 1);
dfs(grid,visited, row, col + 1);
}
// 判断坐标 (row, c) 是否在网格中
bool inArea(vector<vector<char>>& grid, int row, int col) {
return 0 <= row && row < grid.size() && 0 <= col && col < grid[0].size();
}
};
主要是掌握DFS基本结构
从二叉树到网络结构图
三要素:访问相邻结点,判断base case,避免重复遍历
void dfs(vector<vector<char>>& grid,vector<vector<int>>& visited,int row,int col){
// 判断 base case
// 如果坐标 (row, col) 超出了网格范围,直接返回
if (!inArea(grid, row, col)) {
return;
}
//如何避免重复访问,循环绕圈
if(visited[row][col]){//已经被访问过了
return;
}
visited[row][col]=1;//未访问过,标记为访问过
// 访问上、下、左、右四个相邻结点
dfs(grid,visited, row - 1, col);
dfs(grid,visited, row + 1, col);
dfs(grid,visited, row, col - 1);
dfs(grid,visited, row, col + 1);
}
// 判断坐标 (row, col) 是否在网格中
bool inArea(vector<vector<char>>& grid, int row, int col) {
return 0 <= row && row < grid.size() && 0 <= col && col < grid[0].size();
}