HDU 2181 哈密顿绕行世界问题(DFS)

哈密顿绕行世界问题

#include <bits/stdc++.h>
using namespace std;

const int maxn = 25;
int graph[maxn][maxn];
int path[maxn];
int vis[maxn];
int m;
int No;

void dfs(int cur, int cnt, int idx) {
    if(cur == m && cnt == 21) {//找到了
        printf("%d:  ", No);
        for(int i = 0; i < 20; i++) {
            printf("%d ", path[i]);
        }
        printf("%d\n", path[20]);
        No++;
    }

    for(int i = 1; i <= 20; i++) {
        if(graph[cur][i]) {//有路
            if(!vis[i]) {
                vis[i] = 1;
                path[idx] = i;
                dfs(i, cnt+1, idx+1);

                vis[i] = 0;
            }
        }
    }
}
int main() {
    //freopen("data.in", "r", stdin);

    memset(graph, 0, sizeof(graph));

    int x, y, z;
    for(int i = 1; i <= 20; ++i) {
        cin >> x >> y >> z;
        graph[i][x] = graph[x][i] = 1;
        graph[i][y] = graph[y][i] = 1;
        graph[i][z] = graph[z][i] = 1;
    }

    while(cin >> m && m != 0) {
        memset(vis, 0, sizeof(vis));
        memset(path, 0, sizeof(path));

        path[0] = m;
        No = 1;
        dfs(m, 1, 1);
    }

}

阅读更多

没有更多推荐了,返回首页