有n个岛,m班双向航线,航线用x,y表示x和y两个岛之间是有航班的,我要从s岛去t岛,请问是否可以?c++,DFS
输入
3 2 0 2
0 1
1 2
输出
2
bool dfs(int u, int t, vector<bool>& visited, vector<vector<int>>& adj) {
// 到达目的地
if (u == t) {
return true;
}
visited[u] = true;
for (int v : adj[u]) {
if (!visited[v]) {
if (dfs(v, t, visited, adj)) {
//回溯 1!!!!!!!!!!!!!!!
visited[u] = false;
return true;
}
}
}
// 回溯 2!!!!!!!!!!!!!!!!!!!
visited[u] = false;
return false;
}
int main() {
string str;
freopen("test.txt","r",stdin);
int n, m, s, t;
cin >> n >> m >> s >> t;
// 构建邻接表
vector<vector<int>> adj(n);
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
// 深度优先搜索
int count = 0;
int res = 0;
vector<bool> visited(n, false);
for (int i = 0; i < n - 1; i++) {
for(int j = i+1; j < n; j++){
adj[i].push_back(j);
adj[j].push_back(i);
for(auto x : adj){
for(auto y : x){
cout << y << " ";
}
cout <<endl;
}
if(dfs(s, t, visited, adj)){
cout <<" succeed" <<endl;
cout << "i = " <<i <<endl;
cout << "j = " <<j <<endl;
res++;
}
cout <<"-------"<<endl;
adj[i].pop_back();
adj[j].pop_back();
}
}
// 输出结果
cout << res << endl;
return 0;
}