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

https://vjudge.net/problem/HDU-2181

最近写Bfs写的有点多, 猛一下拿到这题就用BFS来写了, 写到后面发现越写越麻烦.

其实就是一道简单的Dfs题目, Dfs的图储存方式通常有两种: 邻接矩阵(bool数组表示通路), 邻接表(用vector来表示该节点相邻接结点)

这道题目比较简单, n也不大, 我直接就用了邻接矩阵来表示

代码如下

//哈密顿绕行世界问题
#include<bits/stdc++.h>
using namespace std;

const int maxn = 25;
bool city[maxn][maxn], vis[maxn]; //表示两个城市间是否能走, 表示一个城市是否走过
int path[maxn], m, no; //路径
void Dfs(int from, int cont)
{
    path[cont] = from;
    if(cont == 20){ //走完了20个城市
        if(city[from][m]){ // 是否到m的路为通路, 打印结果
            printf("%d: ",no++);
            for(int i = 1; i <= 20; i++)
                printf(" %d",path[i]);
            printf(" %d\n", m);
        }
        return;
    }
    //为了从小到大按字典序输出, 对于每个城市我们都判断是否有通路且未走过
    for(int i = 1; i <= 20; i++)
        if(city[from][i] && !vis[i]){
            vis[i] = 1;
            Dfs(i, cont+1);
            vis[i] = 0; //回溯
        }
}

int main()
{
    int i1, i2, i3;
    for(int i = 1; i <= 20; i++){
        scanf("%d%d%d",&i1,&i2,&i3);
        city[i][i1] = 1, city[i][i2] = 1, city[i][i3] = 1;//两城市之间为通路
    }
    while(scanf("%d",&m),m){
        memset(vis, 0, sizeof(vis)), memset(path, 0, sizeof(path));
        no = 1, vis[m] = 1;
        Dfs(m, 1); //初始状态, 从第m个城市出发
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/82930470
今日推荐