-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFSShortestReachinaGraph.cpp
More file actions
99 lines (90 loc) · 2.89 KB
/
Copy pathBFSShortestReachinaGraph.cpp
File metadata and controls
99 lines (90 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <cmath>
#include <climits>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<queue>
class Graph {
private:
std::vector<std::vector<int> > adjacencyList;
int noOfVertex;
int findMinVertex(std::vector<bool> &visited, std::vector<int> &distanceVector){
int minVertex = -1;
int minDist = INT_MAX;
for(int vertex = 0;vertex<noOfVertex;++vertex){
if(!visited[vertex]){
if(minDist>distanceVector[vertex]){
minDist = distanceVector[vertex];
minVertex = vertex;
}
}
}
return minVertex;
}
public:
Graph(int n) {
noOfVertex = n;
adjacencyList.resize(n);
}
void add_edge(int u, int v) {
adjacencyList[u].push_back(v);
adjacencyList[v].push_back(u);
}
std::vector<int> shortest_reach(int currentVertex) {
std::vector<int> distanceVector(noOfVertex, INT_MAX);
std::vector<bool> visited(noOfVertex,false);
distanceVector[currentVertex] = 0;
//apply dikstra algorithm
while(1){
//implement min Function
currentVertex = findMinVertex(visited, distanceVector);
if(currentVertex==-1){
break;
}
visited[currentVertex] = true;
for(int adjacentVertex:adjacencyList[currentVertex]){
if(!visited[adjacentVertex]){
distanceVector[adjacentVertex] = std::min(distanceVector[adjacentVertex], distanceVector[currentVertex]+6);
}
}
}
for(int vertex = 0;vertex<noOfVertex;++vertex){
if(distanceVector[vertex]==INT_MAX){
distanceVector[vertex]=-1;
}
}
return distanceVector;
}
};
int main() {
int queries;
std::cin >> queries;
for (int t = 0; t < queries; t++) {
int n, m;
std::cin >> n;
// Create a graph of size n where each edge weight is 6:
Graph graph(n);
std::cin >> m;
// read and set edges
for (int i = 0; i < m; i++) {
int u, v;
std::cin >> u >> v;
u--, v--;
// add each edge to the graph
graph.add_edge(u, v);
}
int startId;
std::cin >> startId;
startId--;
// Find shortest reach from node s
std::vector<int> distances = graph.shortest_reach(startId);
for (int i = 0; i < distances.size(); i++) {
if (i != startId) {
std::cout << distances[i] << " ";
}
}
std::cout << std::endl;
}
return 0;
}