Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0ffef68

Browse files
Added 0-1 BFS
1 parent 24d1cef commit 0ffef68

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎graph-theory/0-1bfs.cpp‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
***************************
3+
* *
4+
* Author: Swaraj Deep *
5+
* *
6+
***************************
7+
*/
8+
9+
#include <iostream>
10+
#include <vector>
11+
#include <queue>
12+
#include <climits>
13+
#define pi pair<int, int>
14+
15+
using namespace std;
16+
17+
// Single Source Shortest Path when weight is either zero or one
18+
void zero_one_bfs(vector<vector<pi>> &graph, vector<int> &distance, int root, int dist = 0)
19+
{
20+
distance[root] = dist;
21+
deque<int> dq; // Deque for storing nodes
22+
dq.push_front(root);
23+
while (!dq.empty())
24+
{
25+
int vertex = dq.front();
26+
dq.pop_front();
27+
for (pi child : graph[vertex])
28+
{
29+
int u = child.first;
30+
int w = child.second;
31+
// if adding this edge relaxes the previous cost then update it
32+
if (distance[vertex] + w < distance[u])
33+
{
34+
distance[u] = distance[vertex] + w;
35+
// Keep the nodes in sorted order i.e. if weight is one this node is one level down else it is at the same level
36+
if (w == 1)
37+
{
38+
dq.push_back(u);
39+
}
40+
else
41+
{
42+
dq.push_front(u);
43+
}
44+
}
45+
}
46+
}
47+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /