[Backtrack] [leetcode] all possible paths

topic:

For a directed acyclic graph with n nodes, find all paths from 0 to n-1 and output them (in order not required)

The elements in the i-th array of a two-dimensional array represent the next nodes that can be reached by the node i in the directed graph. Cannot go from b→a) Empty means there is no next node.

Example 1:

Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths 0 -> 1 -> 3 and 0 -> 2 -> 3

source:

797. All possible paths

Problem-solving ideas: backtracking

Note: The directed acyclic graph graph[i] represents the set of nodes that can be reached by node i.

Define an array path to store all nodes that can be reached from node 0, and first put node 0 into the array.

  • Recursive termination condition: when the last number of path is the maximum
  • The result meets the condition: when the recursion terminates
class Solution {
public:
    vector< vector<int> > result;
    vector<int> path;
    vector< vector<int> > allPathsSourceTarget(vector<vector<int>>& graph) {
        path.push_back(0);
        back(graph);
        return result;
    }
    void back(const vector< vector<int> >& graph) {
        int pre = path[path.size() - 1];
        if (pre == graph.size() - 1) {
            result.push_back(path);
            return;
        }
        // 上一节点能够到达的节点集合,每个都尝试一次
        for (int i = 0; i < graph[pre].size(); i++) {
            path.push_back(graph[pre][i]);
            back(graph);
            path.pop_back();
        }
    }
};

 

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/115046629