理论基础:
第一题、所有可能的路径 力扣题目链接
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void dfs(vector<vector<int>>& graph, int x){
if(x == graph.size() - 1){
result.push_back(path);
return;
}
for(int i = 0; i < graph[x].size(); i++){
path.push_back(graph[x][i]);
dfs(graph, graph[x][i]);
path.pop_back();
}
}
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
path.push_back(0);
dfs(graph, 0);
return result;
}
};
第二题、岛屿数量 力扣题目链接
深搜版:
class Solution {
private:
int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 加减1控制4个方向
void dfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y){
for(int i = 0; i < 4; i++){
int nextx = x + dir[i][0];
int nexty = y + dir[i][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 n = grid.size(), m = grid[0].size();
vector<vector<bool>> visited = vector<vector<bool>>(n, vector<bool>(m, false));
int result = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(!visited[i][j] && grid[i][j] == '1'){
visited[i][j] = true;
result++;
dfs(grid, visited, i, j);
}
}
}
return result;
}
};
广搜版:
class Solution {
private:
int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1}; // 加减1控制4个方向
void bfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y){
queue<pair<int, int>> que;
que.push({x, y});
visited[x][y] = true; // 立刻标记
while(!que.empty()){
pair<int, int> cur = que.front(); que.pop();
int curx = cur.first;
int cury = cur.second;
for(int i = 0;i < 4; i++){
int nextx = curx + dir[i][0];
int nexty = cury + dir[i][1];
if(nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
if(!visited[nextx][nexty] && grid[nextx][nexty] == '1'){
que.push({nextx, nexty});
visited[nextx][nexty] = true; // 加入队列 立刻标记
}
}
}
}
public:
int numIslands(vector<vector<char>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<vector<bool>> visited = vector<vector<bool>>(n, vector<bool>(m, false));
int result = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (!visited[i][j] && grid[i][j] == '1') {
result++; // 遇到没访问过的陆地,+1
bfs(grid, visited, i, j); // 将与其链接的陆地都标记上 true
}
}
}
return result;
}
};