Leetcode 797. 所有可能的路径 (DFS回溯搜索)

这是一个典型的DFS回溯搜索,图中所给数据是临接表,图的搜素需要借助一个visted数组判断每个点是否访问过。从0开始搜索,可以走1,也可以走2,直到走到3结束。所以有一个回溯的过程,这里的代码非常经典

注意,必须用if和else不能直接return,因为必须搜索完所有的路径才能return。

class Solution {
public:
    vector<vector<int>> res;
    vector<int> path;
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        vector<bool> visited(graph.size());
        dfs(graph,0,visited);
        return res;
    }

    void dfs(vector<vector<int>>& graph, int index, vector<bool> &visited){
        visited[index] = true;
        path.push_back(index);
        if(index==visited.size()-1){
            res.push_back(path);
        }else{
            for(auto v:graph[index]){
                if(!visited[v]) dfs(graph,v,visited);
            }
        }
        visited[index] = false;
        path.pop_back();
    }
};

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/112875528