【简单的dijkstar】PTA 7-3 最短路径 (20分)

发现没什么人写这种基础代码的blog,不带教学记录一下自己写的。
明明是简单的东西但是有的时候脑子就是转不过来,乌鱼子

最短路径 (20分)

给定一个有N个顶点和E条边的无向图,顶点从0到N−1编号。请判断给定的两个顶点之间是否有路径存在。如果存在,给出最短路径长度。 这里定义顶点到自身的最短路径长度为0。 进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。

输入格式:
输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。 随后E行,每行给出一条边的两个顶点。每行中的数字之间用1空格分隔。 最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。

输出格式:
如果i和j之间存在路径,则输出"The length of the shortest path between i and j is X.",X为最短路径长度, 否则输出"There is no path between i and j."。

输入样例1:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 3

输出样例1:

The length of the shortest path between 0 and 3 is 2.

输入样例2:

7 6
0 1
2 3
1 4
0 2
1 3
5 6
0 6

输出样例2:

There is no path between 0 and 6.

代码
基础dijkstar实现

#include <stdio.h>
int m,n,end,had[11]={0},len[11]={0},path[11][11]={0};
void bdPath(int start,int pathL){
    int i,size=0,temp[11];
    for(i=0;i<m;i++){
        if(path[start][i]==1&&had[i]==0){
            len[i]=pathL;
            had[i]=1;
            temp[size++]=i;
            //printf("%d %d\n",i,pathL);
            if(i==end)
                return;
        }
    }
    while(size--){
        bdPath(temp[size],pathL+1);
    }
}
int main(){
    int i,a,b;
    scanf("%d %d",&m,&n);
    for(i=0;i<n;i++){
        scanf("%d %d",&a,&b);
        path[a][b]=path[b][a]=1;
    }
    int start;
    scanf("%d %d",&start,&end);
    had[start]=1;
    len[start]=0;
    bdPath(start,1);
    if(had[end]==0){
        printf("There is no path between %d and %d.",start,end);
    }
    else{
        printf("The length of the shortest path between %d and %d is %d.",start,end,len[end]);
    }
}
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值