xinyu04

导航

LeetCode 797 All Paths From Source to Target 回溯

Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.

The graph is given as follows: graph[i] is a list of all nodes you can visit from node \(i\) (i.e., there is a directed edge from node \(i\) to node graph[i][j]).

Solution

求一个点到终点的每条路径。对于边的存储我们依然是用 \(vector\),为了遍历每一种情况,在 \(DFS\) 的时候,记得 \(pop\_back\)

点击查看代码
class Solution {
private:
    
    vector<vector<int>> ans;
    
    void dfs(int from, int tgt, vector<vector<int>> graph, vector<int>& path, vector<vector<int>>& ans){
        path.push_back(from);
        if(from==tgt){
            ans.push_back(path); return;
        }
        for(auto to: graph[from]){
            dfs(to, tgt, graph, path, ans);
            path.pop_back();
        }
        
    }
    
public:
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        int sz = graph.size();
        vector<int> path;
        
        dfs(0, sz-1, graph, path, ans);
        return ans;
    }
};

posted on 2022-08-07 02:59  Blackzxy  阅读(12)  评论(0编辑  收藏  举报