N개의 노드가 있는 방향성 순환 그래프가 있다고 가정합니다. 노드 0에서 노드 N-1까지 가능한 모든 경로를 찾아 원하는 순서로 반환해야 합니다. 그래프는 다음과 같이 주어집니다. 노드는 0, 1, ..., graph.length - 1입니다. graph[i]는 가장자리(i, j)가 존재하는 모든 노드 j의 목록입니다.
따라서 입력이 [[1,2], [3], [3], []]와 같으면 출력은 [[0,1,3], [0,2,3]]이 됩니다.피>
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
res
라는 하나의 2차원 배열을 만듭니다. -
solve라는 메서드를 정의하면 그래프, 노드, 대상 및 임시 배열이 사용됩니다.
-
임시 노드에 삽입
-
노드가 대상이면 res에 temp를 삽입하고 반환합니다.
-
범위 0에서 그래프[노드] 크기까지의 i에 대해 – 1
-
solve(graph, graph[node, i], target, temp) 호출
-
-
메인 메소드 create array temp에서 solve(graph, 0, size of graph - 1, temp)
를 호출합니다. -
반환 해상도
예시(C++)
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector < vector <int> > res;
void solve(vector < vector <int> >& graph, int node, int target, vector <int>temp){
temp.push_back(node);
if(node == target){
res.push_back(temp);
return;
}
for(int i = 0; i < graph[node].size(); i++){
solve(graph, graph[node][i], target, temp);
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector <int> temp;
solve(graph, 0, graph.size() - 1, temp);
return res;
}
};
main(){
vector<vector<int>> v = {{1,2},{3},{3},{}};
Solution ob;
print_vector(ob.allPathsSourceTarget(v));
} 입력
[[1,2],[3],[3],[]]
출력
[[0, 1, 3, ],[0, 2, 3, ],]