hdu2181 哈密頓繞行世界問題 水題 dfs深搜列舉
阿新 • • 發佈:2018-12-02
本身就是一個簡單的深搜列舉問題,這裡主要是提醒自己關於遞迴函式關於遞迴次數的理解
自己腦抽了一直沒注意到這個問題,連樣例都沒過。最後發現問題。
程式碼:
#include<iostream> #include<cstdio> #include<stack> #include<vector> #include<cstdlib> #include<cstring> using namespace std; vector<int>vec[20]; int vis[30], path[30]; int kase = 0; void dfs(int x, int tar, int cnt) { if (x == tar && cnt == 20) { printf("%d: ", ++kase); stack<int>iron; iron.push(x); while (path[x] != -1) { iron.push(path[x]); x = path[x]; if (x == tar) break; } while (iron.size()!=1) { int t = iron.top(); iron.pop(); printf("%d ", t); } printf("%d", iron.top()); printf("\n"); return; } for (int i = 0; i < vec[x].size(); i++) { int t = vec[x][i]; if (t == x) continue; if (vis[t]) continue; if (t == tar && cnt != 19) continue; path[t] = x; vis[t] = 1; dfs(t, tar, cnt + 1); path[t] = -1; vis[t] = 0; } } void ini() { memset(vis, 0, sizeof(vis)); memset(path, -1, sizeof(path)); } int main() { for (int i = 1; i <= 20; i++) { int a, b, c; scanf("%d %d %d", &a, &b, &c); vec[i].push_back(a); vec[i].push_back(b); vec[i].push_back(c); } int m; //scanf("%d", &m); ini(); while (scanf("%d", &m) && m != 0) { for (int i = 0; i < vec[m].size(); i++) { int t = vec[m][i]; vis[t] = 1; path[t] = m; dfs(t, m, 1); vis[t] = 0; path[t] = -1; } } //system("pause"); return 0; }