UVA208Firetruck 消防车(图的路径搜索)
生活随笔
收集整理的這篇文章主要介紹了
UVA208Firetruck 消防车(图的路径搜索)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:輸入一個n(n20)個節點的無向圖以及某個結點k,按照字典序從小到大順序輸出從結點1到結點k的所有路徑,要求經過結點不能重復經過。
分析:終于做到水題了,此題唯一要點就是先判斷是否能到達,用dfs。
#include<cstdio> #include<cstring> #include<cctype> #include<queue> #include<iostream> #include<vector> #include<list> #include<set> using namespace std; const int maxn = 20+5; int G[maxn][maxn], vis[maxn]; int k,m; int allroute; int routemap[400][maxn]; void solve(int cur,int dep) {if (cur == k) {for (int i = 0; i < dep-1; i++) {cout << routemap[allroute][i] << " ";}cout << routemap[allroute][dep - 1];cout << endl;allroute++;memcpy(routemap[allroute], routemap[allroute - 1], sizeof(routemap[allroute - 1]));return;}for (int i = 1; i <= m; i++) {if (G[cur][i]&&!vis[i]) {vis[i] = 1;routemap[allroute][dep] = i;solve(i, dep + 1);vis[i] = 0;}} } bool isarrive(int cur) {if (cur == k) {return true;}for (int i = 1; i <= m; i++) {if (G[cur][i] && !vis[i]) {vis[i] = 1;if (isarrive(i))return true;}}return false; } int main() {int a, b; int kase = 0;while (cin >> k && k) {++kase;memset(G, 0, sizeof(G));memset(vis, 0, sizeof(vis));m = 0; allroute = 0;while (cin >> a >> b && a&&b) {G[a][b] = 1;G[b][a] = 1;m = max(max(a, b), m);}cout << "CASE " << kase << ":" << endl;if (isarrive(1)) {memset(vis, 0, sizeof(vis));vis[1] = 1;routemap[allroute][0] = 1;solve(1, 1);cout << "There are "<<allroute<< " routes from the firestation to streetcorner " << k << "." << endl;}else {//不可達cout << "There are 0 routes from the firestation to streetcorner " << k << "." << endl;}}//system("pause");return 0; }?
總結
以上是生活随笔為你收集整理的UVA208Firetruck 消防车(图的路径搜索)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UVA1603Square Destro
- 下一篇: UVA225Golygons 黄金图形