-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathSimpleGraphTemplate.cpp
More file actions
73 lines (56 loc) · 1.53 KB
/
SimpleGraphTemplate.cpp
File metadata and controls
73 lines (56 loc) · 1.53 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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
template <typename T>
class Graph {
private:
vector<vector<T>> adj_list;
bool directed;
public:
Graph(int n, bool is_directed = false) : adj_list(n), directed(is_directed) {}
void add_edge(const T& u, const T& v) {
adj_list[u].push_back(v);
if (!directed) {
adj_list[v].push_back(u);
}
}
vector<int> bfs(const T& start, const vector<bool>& landmines) {
vector<int> distance(adj_list.size(), -1);
distance[start] = 0;
queue<T> q;
q.push(start);
while (!q.empty()) {
T current_node = q.front();
q.pop();
for (const T& neighbor : adj_list[current_node]) {
if (distance[neighbor] == -1 && !landmines[neighbor]) {
distance[neighbor] = distance[current_node] + 1;
q.push(neighbor);
}
}
}
return distance;
}
};
int main() {
int N, M;
cin >> N >> M;
int source, target;
cin >> source >> target;
vector<bool> landmines(N);
for (int i = 0; i < N; ++i) {
int has_landmine;
cin >> has_landmine;
landmines[i] = (has_landmine == 1);
}
Graph<int> g(N, false); // Undirected graph
for (int i = 0; i < M; ++i) {
int u, v;
cin >> u >> v;
g.add_edge(u, v);
}
vector<int> distances = g.bfs(source, landmines);
cout << distances[target] << "\n";
return 0;
}