สมมติว่าเรามีกราฟ acyclic กำกับที่มีโหนด N เราต้องหาเส้นทางที่เป็นไปได้ทั้งหมดจากโหนด 0 ถึงโหนด N-1 และส่งคืนในลำดับใดก็ได้ กราฟมีดังต่อไปนี้ โหนดคือ 0, 1, ..., graph.length - 1. graph[i] คือรายการของโหนดทั้งหมด j ที่มี edge (i, j) อยู่
ดังนั้นหากอินพุตเป็นเหมือน [[1,2], [3], [3], []] เอาต์พุตจะเป็น [[0,1,3], [0,2,3]]พี>
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
-
สร้างอาร์เรย์ 2d หนึ่งรายการที่เรียกว่า res
-
กำหนดวิธีการที่เรียกว่า Solve ซึ่งจะใช้กราฟ โหนด เป้าหมาย และอาร์เรย์ชั่วคราว
-
แทรกโหนดลงในอุณหภูมิ
-
หากโหนดเป็นเป้าหมาย ให้แทรก temp ลงใน res แล้วส่งคืน
-
สำหรับฉันอยู่ในช่วง 0 ถึงขนาดของกราฟ[โหนด] – 1
-
แก้การโทร (กราฟ, กราฟ[โหนด, i], เป้าหมาย, อุณหภูมิ)
-
-
จากเมธอดหลัก สร้างอาร์เรย์ temp, call 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, ],]