「代码随想录算法训练营」第四十三天 | 图论 part1
  3HyMPPhAWYCC 29天前 42 0

797. 所有可能的路径

题目链接:https://leetcode.cn/problems/all-paths-from-source-to-target/description/
文章讲解:https://programmercarl.com/kamacoder/0098.所有可达路径.html
题目难度:中等
题目状态:看题解

思路一:DFS

void dfs(vector<vector<int>> &graph, int x, int n)
使用深度优先搜索(DFS)方法,用于探索从节点x到节点n的所有路径。
逻辑:

  • 如果当前节点x是目标节点n,将当前路径stk添加到ans中。
  • 遍历graph[x]中的每个相邻节点y
    • 将节点y添加到当前路径stk
    • 递归调用dfs以继续探索从y开始的路径。
    • 回溯:从stk中移除节点y,以探索其他可能的路径。

vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph)
这是解决问题的主方法,返回从起点到终点的所有路径。
逻辑:
将起点0添加到当前路径stk
调用dfs方法,从起点0开始探索到终点n的路径。
返回存储了所有路径的ans

代码一:

class Solution {
public:
    vector<vector<int>> ans;
    vector<int> stk;

    void dfs(vector<vector<int>> &graph, int x, int n) {
        if(x == n) {
            ans.push_back(stk);
            return;
        }
        for(auto &y : graph[x]) {
            stk.push_back(y);
            dfs(graph, y, n);
            stk.pop_back();
        }
    }

    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        stk.push_back(0);
        dfs(graph, 0, graph.size() - 1);
        return ans;
    }
};

消耗一:

image

思路二:BFS

  1. 初始化:
    • 创建一个队列 q 来存储路径。
    • 将初始路径 {0}(只包含起点)放入队列。
  2. 目标节点:
    • 设定目标节点为 target = graph.size() - 1,即图的最后一个节点。
  3. BFS循环:
    • 当队列不为空时,执行以下步骤:
      • 从队列中取出一个路径 path。
      • 获取路径的最后一个节点 lastNode。
      • 如果 lastNode 是目标节点,将当前路径加入结果 ans。
      • 否则,遍历 lastNode 的所有相邻节点 nextNode:
        • 创建一个新路径 newPath,将 nextNode 添加到 path。
        • 将 newPath 放入队列。
  4. 返回结果:
    • 当队列为空时,所有路径都已找到,返回结果 ans。

代码二:

class Solution {
public:
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        vector<vector<int>> ans;
        queue<vector<int>> q;
        q.push({0});
        int target = graph.size() - 1;
        while(!q.empty()) {
            vector<int> path = q.front();
            q.pop();
            int lastNode = path.back();
            if(lastNode == target) ans.push_back(path);
            else {
                for(auto &nextNode : graph[lastNode]) {
                    vector<int> newPath = path;
                    newPath.push_back(nextNode);
                    q.push(newPath);
                }
            }
        }
        return ans;
    }
};

消耗二:

image

ACM模式

题目链接:https://kamacoder.com/problempage.php?pid=1170

邻接矩阵代码:

#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> result; // 收集符合条件的路径
vector<int> path; // 1节点到终点的路径

void dfs (const vector<vector<int>>& graph, int x, int n) {
    // 当前遍历的节点x 到达节点n 
    if (x == n) { // 找到符合条件的一条路径
        result.push_back(path);
        return;
    }
    for (int i = 1; i <= n; i++) { // 遍历节点x链接的所有节点
        if (graph[x][i] == 1) { // 找到 x链接的节点
            path.push_back(i); // 遍历到的节点加入到路径中来
            dfs(graph, i, n); // 进入下一层递归
            path.pop_back(); // 回溯,撤销本节点
        }
    }
}

int main() {
    int n, m, s, t;
    cin >> n >> m;

    // 节点编号从1到n,所以申请 n+1 这么大的数组
    vector<vector<int>> graph(n + 1, vector<int>(n + 1, 0));

    while (m--) {
        cin >> s >> t;
        // 使用邻接矩阵 表示无线图,1 表示 s 与 t 是相连的
        graph[s][t] = 1;
    }

    path.push_back(1); // 无论什么路径已经是从0节点出发
    dfs(graph, 1, n); // 开始遍历

    // 输出结果
    if (result.size() == 0) cout << -1 << endl;
    for (const vector<int> &pa : result) {
        for (int i = 0; i < pa.size() - 1; i++) {
            cout << pa[i] << " ";
        }
        cout << pa[pa.size() - 1]  << endl;
    }
}

邻接表代码:

#include <iostream>
#include <vector>
#include <list>
using namespace std;

vector<vector<int>> result; // 收集符合条件的路径
vector<int> path; // 1节点到终点的路径

void dfs (const vector<list<int>>& graph, int x, int n) {

    if (x == n) { // 找到符合条件的一条路径
        result.push_back(path);
        return;
    }
    for (int i : graph[x]) { // 找到 x指向的节点
        path.push_back(i); // 遍历到的节点加入到路径中来
        dfs(graph, i, n); // 进入下一层递归
        path.pop_back(); // 回溯,撤销本节点
    }
}

int main() {
    int n, m, s, t;
    cin >> n >> m;

    // 节点编号从1到n,所以申请 n+1 这么大的数组
    vector<list<int>> graph(n + 1); // 邻接表
    while (m--) {
        cin >> s >> t;
        // 使用邻接表 ,表示 s -> t 是相连的
        graph[s].push_back(t);

    }

    path.push_back(1); // 无论什么路径已经是从0节点出发
    dfs(graph, 1, n); // 开始遍历

    // 输出结果
    if (result.size() == 0) cout << -1 << endl;
    for (const vector<int> &pa : result) {
        for (int i = 0; i < pa.size() - 1; i++) {
            cout << pa[i] << " ";
        }
        cout << pa[pa.size() - 1]  << endl;
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 29天前 0

暂无评论

推荐阅读
  cA1FqmrigEPj   12天前   37   0   0 算法与数据结构
3HyMPPhAWYCC