题解 | #【模板】单源最短路1#

【模板】单源最短路1

https://www.nowcoder.com/practice/f24504c9ff544f7c808f76693cc34af8

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

const int N = 5100;

struct Node
{
    int id;
    int step;
    Node() {}
    Node(int _id, int _step) :id(_id), step(_step) {}
};

vector<int> graph[N];
vector<int> vis(N);

int n, m;

int BFS(int start, int step)
{
    Node node(start, step);
    queue<Node> que;
    que.push(node);
    vis[start] = 1;
    while (!que.empty())
    {
        Node s = que.front();
        que.pop();
        if (s.id == n)
        {
            return s.step;
        }
        for (int i = 0; i < graph[s.id].size(); i++)
        {
            if (vis[graph[s.id][i]] == 0)
            {
                vis[graph[s.id][i]] = 1;
                que.push(Node(graph[s.id][i], s.step + 1));
            }
        }
    }
    return -1;
}

int main()
{
    cin >> n >> m;
    int x, y;
    for (int i = 0; i < m; i++)
    {
        cin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    cout << BFS(1, 0) << endl;
    return 0;
}
全部评论

相关推荐

03-19 17:49
运营
牛客327038019号:你把那贼低的gpa写上去干嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务