当出差遇上大雾

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LYKXHTP/article/details/88844824

当出差遇上大雾

题目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
本题考察深度优先搜索DFS,C++代码如下:

#include<bits/stdc++.h>

const int inf=0x7f7f7f7f;
//在int型中0x7f7f7f7f也就是无穷大
int d[50];
int a[][7] = {
    {0},
    {0, 0, 2, 10, 5, 3, -1},
    {0, -1, 0, 12, -1, -1, 10},
    {0, -1, -1, 0, -1, 7, -1},
    {0, 2, -1, -1, 0, 2, -1},
    {0, 4, -1, -1, 1, 0, -1},
    {0, 3, -1, 1, 0, 2, 0},
};

int x,y;
int res;
int used[10];
int ans=inf;
int ansp;//经过的城市数量
int ansd[50];//保存经过的城市

void dfs(int now,int cost,int p){
    if(now==x){
        if(cost<ans){
            ans=cost;
            for(int i=0;i<p;i++){
                ansd[i]=d[i];
            }
            ansp=p;
        }
    }
    for(int i=1;i<=6;i++){
        if(i==y){
            continue;
        }
        if(used[i]==0 && a[now][i]>=0){
            //使用回溯法进行DFS
            used[i]=1;
            d[p]=i;
            dfs(i,cost+a[now][i],p+1);
            used[i]=0;
        }
    }
}

int main()
{
    static char emp[]="";
    static char col[]=", ";
    scanf("%d%d",&x,&y);
    //出差城市x(x可为1,2,3,4,6)
    //大雾城市y(y可为0,1,2,3,4,5,6,为0时代表没有城市出现大雾)
    if(x==5){
        printf("0\n[]\n");
    }else{
        d[0]=5;
        used[5]=1;
        dfs(5,0,1);
        char *p=emp;
        if(ans==inf){
            printf("1000\n[]\n");
        }else{
            printf("%d\n[",ans);
            for(int i=0;i<ansp;i++){
                printf("%s%d",p,ansd[i]);
                p=col;
            }
            printf("]\n");
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/LYKXHTP/article/details/88844824
今日推荐