Message Route

Syrjälä's network has n computers and m connections. Your task is to find out if Uolevi can send a message to Maija, and if it is possible, what is the minimum number of computers on such a route.

Example:

Input: n = 5, m = 5, edges = {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {5, 4}}

Output:

3 1 4 5

Approach:

C++

#include <bits/stdc++.h>
using namespace std;
vector<intarr[2000111];
int vis[2000011];
int dist[2000011];
int parent[2000011];
void bfs(int node)
{
    queue<intq;
    q.push(node);
    vis[node] = 1;
    parent[node] = -1;
    dist[node] = 1;
    while (!q.empty())
    {
        int curr = q.front();
        q.pop();
        for (int child : arr[curr])
        {
            if (vis[child] == 0)
            {
                vis[child] = 1;
                parent[child] = curr;
                dist[child] = dist[curr] + 1;
                q.push(child);
            }
        }
    }
}
int main()
{
    int n = 5m = 5;
    vector<vector<int>> edges = {{12}, {13}, {14}, 
{23}, {54}};
    for (int i = 0i < mi++)
    {
        int a = edges[i][0]b = edges[i][1];

        arr[a].push_back(b);
        arr[b].push_back(a);
    }
    bfs(1);
    if (vis[n] == 0)
        cout << "IMPOSSIBLE\n";
    else
    {
        cout << dist[n<< "\n";
        vector<intpath;
        for (int v = nv != -1v = parent[v])
            path.push_back(v);
        for (int i = path.size() - 1i >= 0i--)
            cout << path[i] << " ";
        cout << "\n";
    }
    return 0;
}


No comments:

Post a Comment