Consider an undirected graph where each edge weighs 6 units. Each of the nodes is labeled consecutively from 1 to n.
You will be given a number of queries. For each query, you will be given a list of edges describing an undirected graph. After you create a representation of the graph, you must determine and report the shortest distance to each of the other nodes from a given starting position using the breadth-first search algorithm (BFS). Return an array of distances from the start node in node number order. If a node is unreachable, return - 1 for that node.
You will be given a number of queries. For each query, you will be given a list of edges describing an undirected graph. After you create a representation of the graph, you must determine and report the shortest distance to each of the other nodes from a given starting position using the breadth-first search algorithm (BFS). Return an array of distances from the start node in node number order. If a node is unreachable, return - 1 for that node.
Example:
Input: n=4,m=2 ,edges={{1,2},{1,3}}, s=1
Output: 6 6 -1
Approach
C++
#include <bits/stdc++.h>using namespace std;vector<int> arr[1000001];int vis[1000001];int dist[1000001];void bfs(int node){queue<int> q;q.push(node);dist[node] = 0;vis[node] = 1;while (!q.empty()){int curr = q.front();q.pop();for (int child : arr[curr]){if (vis[child] == 0){dist[child] = dist[curr] + 6;vis[child] = 1;q.push(child);}}}}int main(){int n = 4, m = 2;for (int i = 1; i <= n; i++){arr[i].clear();vis[i] = 0;}arr[1].push_back(2);arr[2].push_back(1);arr[1].push_back(3);arr[3].push_back(1);int s = 1;bfs(s);for (int i = 1; i <= n; i++){if (i == s)continue;if (vis[i] == 0)cout << -1 << " ";elsecout << dist[i] << " ";}cout << "\n";return 0;}
No comments:
Post a Comment