-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBFS.cpp
More file actions
35 lines (28 loc) · 711 Bytes
/
BFS.cpp
File metadata and controls
35 lines (28 loc) · 711 Bytes
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
// BFS
//
// Encontra o menor caminho de um ponto a outro.
// Parecido com o Dijkstra porem mais eficiente
// já que cada aresta só tem peso 0 ou 1.
// O(n)
#define INF 0x3f3f3f3f
vector<vector<pair<int,int>>> adj;
int bfs_01(int n, int s) {
vector<int> dist(n, INF);
dist[s] = 0;
deque<int> q;
q.push_front(s);
while (!q.empty()) {
int u = q.front();
q.pop_front();
for (const auto& [v,w] : adj[u]) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
if (w == 1)
q.push_back(v);
else
q.push_front(v);
}
}
}
return dist[n-1];
}