//题目:深度优先搜索
//
//给定一个无向图,使用深度优先搜索算法找到从给定起始节点到目标节点的路径。
//
//问题函数定义:
//
//cpp
//vector<int> dfs(vector<vector<int>>& graph, int start, int target);
//裁判测试程序样例:
//
//cpp
#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
using namespace std;
#define maxsize 100
vector<int> vi(maxsize);
vector<int> m;
void dfs(vector<vector<int>>& graph, int current, int target) {
vi[current] = 1;
m.push_back(current);
if (current == target) {
return;
}
for (int next : graph[current]) {
if (!vi[next]) {
dfs(graph, next, target);
if (m.back() == target) {
return;
}
}
}
m.pop_back();//******************************************************************************************
}
vector<int> findPath(vector<vector<int>>& graph, int start, int target) {
dfs(graph, start, target);
return m;
}
int main() {
vector<vector<int>> graph = { {1, 2}, {0, 3, 4}, {0, 5}, {1}, {1, 6, 7}, {2}, {4, 8}, {4, 9}, {6}, {7} };
int start = 0, target = 5;
vector<int> path = findPath(graph, start, target);
if (path.empty()) {
cout << "No path found!" << endl;
}
else {
cout << "Path from " << start << " to " << target << ": ";
for (int node : path) {
cout << node << " ";
}
cout << endl;
}
return 0;
}
//输入样例:
//
//0 5
//输出样例:
//
//Path from 0 to 5: 0 2 5