C++打卡7-最短距离

题目描述

给定一个无向图,求出从起点到终点的最短距离(每条边计1)。

输入格式:

第一行:n(点数)、m(边数)、sx(起点)、fx(终点)

接下来m行:x、y,表示一条边

输出格式:

一个数字,从sx到fx的最短距离(经过边的数目)

如果不能到达输出0

输入样例:

7 9 1 6

1 2

1 7

2 3

2 5

3 4

3 6

4 5

5 6

6 7

输出样例:

2

数据范围:

60%:1<=n<=15, 1<=m<=50

100%:1<=n<=1000, 1<=m<=5000

代码(鸡汤)来咯~

#include <bits/stdc++.h>

using namespace std;

const int N=1005;

vector<int> g[N];

bool vis[N];

int c[N];

int n,m,sx,fx;

void dfs(int x){

    queue<int>q;

    vis[x];

    q.push(x);

    while(!q.empty()){

        int x=q.front();

        if(x==fx) return;

        q.pop();

        for(int i=0;i<g[x].size();i++){

            int y=g[x][i];

            if(vis[y]==1) continue;

            vis[y]=1;

            c[y]=c[x]+1;

            q.push(y);

        }

    }

}

int main(){

    cin>>n>>m>>sx>>fx;

    for(int i=1;i<=m;i++){

        int x,y;

        cin>>x>>y;

        g[x].push_back(y);

        g[y].push_back(x);

    }dfs(sx);

    cout<<c[fx];

    return 0;

}

不多不少,好极了!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值