forked from vaibhavpathak999/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
62 lines (52 loc) · 1.2 KB
/
Copy pathBFS.cpp
File metadata and controls
62 lines (52 loc) · 1.2 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
#include <bits/stdc++.h>
using namespace std;
const int N = 1'00'000; // maximum number of nodes
vector<int> adj[N]; //adjacency list
int dis[N];
bool pushed_in_queue[N]; // visited
int main() {
int n; // nodes
cin >> n;
int m; // edges
cin >> m;
for (int i = 0; i < m; ++i) {
int x, y;
cin >> x >> y; // represents edge between x and y
// Undirected
adj[x].push_back(y);
adj[y].push_back(x);
}
// lets say we have to run bfs from 1
queue<int> q;
q.push(1); // fixed vertex
dis[1] = 0;
pushed_in_queue[1] = true;
while (!q.empty()) {
int node = q.front(); // currently visiting this node
q.pop(); // dont want to visit this again
// Go through all children
for (int x : adj[node]) {
if (pushed_in_queue[x] == true) continue;
q.push(x); //visit x later
dis[x] = dis[node] + 1;
pushed_in_queue[node] = true; // to make sure we dont visit twice
}
}
cout << dis[10]; // must be 3
return 0;
}
/*
? Example:
10 10
1 2
1 3
1 4
2 5
2 6
3 7
3 8
4 9
6 10
7 10
*/
// inside queue: [0] [1 1 1] [2 2 2 2 2] [3]