所有可能的路径:
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public:
vector<int> path;
vector<vector<int>> result;
void dfs(vector<vector<int>> graph, int x){//1 确认递归函数和参数
if (x == graph.size()-1) {//2 确认终止条件
result.push_back(path);
return;
}
for (int i = 0; i < graph[x].size(); i++) {//3 处理目前搜索节点出发的路径
path.push_back(graph[x][i]);//把当前节点压入
dfs(graph, graph[x][i]);//递归
path.pop_back();//回溯
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
path.push_back(0);//初始节点0要加入
dfs(graph, 0);//从初始节点开始递归
return result;
}
};
bfs:
用队列实现:
岛屿数量
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
dfs:
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 判断岛屿数量
* @param grid char字符型vector<vector<>>
* @return int整型
*/
int dir[4][2] = {1,0, 0,1, -1,0, 0,-1};
void dfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x, int y) {
for (int i = 0; i < 4; i++) {
int newX = x + dir[i][0];
int newY = y + dir[i][1];
if (newX < 0 || newX >= grid.size() || newY < 0 || newY >= grid[0].size()) continue;
if (!visited[newX][newY] && grid[newX][newY] == '1') {
visited[newX][newY] = true;
dfs(grid, visited, newX, newY);
}
}
}
int solve(vector<vector<char> >& grid) {
// write code here
vector<vector<bool>> visited(grid.size(), vector<bool> (grid[0].size(), false));
int count = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (!visited[i][j] && grid[i][j] == '1') {
count++;
visited[i][j] = true;
dfs(grid, visited, i, j);
}
}
}
return count;
}
};
bfs:
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 判断岛屿数量
* @param grid char字符型vector<vector<>>
* @return int整型
*/
int dir[4][2] = {1,0, 0,1, -1,0, 0,-1};
void bfs(vector<vector<char>>& grid, vector<vector<bool>>& visited, int x,int y) {
queue<pair<int, int>> que;
que.push(pair(x, y));
visited[x][y] = true;
while (!que.empty()) {
int curX = que.front().first;
int curY = que.front().second;
que.pop();
for(int i = 0; i < 4; i++) {
int newX = curX + dir[i][0];
int newY = curY + dir[i][1];
if (newX < 0 || newX >= grid.size() || newY < 0 || newY >= grid[0].size()) continue;
if (!visited[newX][newY] && grid[newX][newY] == '1') {
que.push(pair(newX, newY));
visited[newX][newY] = true;
}
}
}
}
int solve(vector<vector<char> >& grid) {
// write code here
vector<vector<bool>> visited(grid.size(), vector<bool> (grid[0].size(), false));
int count = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (!visited[i][j] && grid[i][j] == '1') {
count++;
bfs(grid, visited, i, j);
}
}
}
return count;
}
};