Syrjälä's network has computers and 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<int> arr[2000111];int vis[2000011];int dist[2000011];int parent[2000011];void bfs(int node){queue<int> q;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 = 5, m = 5;vector<vector<int>> edges = {{1, 2}, {1, 3}, {1, 4},{2, 3}, {5, 4}};for (int i = 0; i < m; i++){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<int> path;for (int v = n; v != -1; v = parent[v])path.push_back(v);for (int i = path.size() - 1; i >= 0; i--)cout << path[i] << " ";cout << "\n";}return 0;}
No comments:
Post a Comment