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 1cbbd5f

Browse files
kHarshitpoyea
authored andcommitted
Added BFS and DFS (graph algorithms) (TheAlgorithms#408)
* feat: Add Breadth First Search (graph algorithm) * feat: Add Depth First Search (graph algorithm)
1 parent 42d42c3 commit 1cbbd5f

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

‎Graphs/BFS.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""pseudo-code"""
2+
3+
"""
4+
BFS(graph G, start vertex s):
5+
// all nodes initially unexplored
6+
mark s as explored
7+
let Q = queue data structure, initialized with s
8+
while Q is non-empty:
9+
remove the first node of Q, call it v
10+
for each edge(v, w): // for w in graph[v]
11+
if w unexplored:
12+
mark w as explored
13+
add w to Q (at the end)
14+
15+
"""
16+
17+
import collections
18+
19+
20+
def bfs(graph, start):
21+
explored, queue = set(), [start] # collections.deque([start])
22+
explored.add(start)
23+
while queue:
24+
v = queue.pop(0) # queue.popleft()
25+
for w in graph[v]:
26+
if w not in explored:
27+
explored.add(w)
28+
queue.append(w)
29+
return explored
30+
31+
32+
G = {'A': ['B', 'C'],
33+
'B': ['A', 'D', 'E'],
34+
'C': ['A', 'F'],
35+
'D': ['B'],
36+
'E': ['B', 'F'],
37+
'F': ['C', 'E']}
38+
39+
print(bfs(G, 'A'))

‎Graphs/DFS.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""pseudo-code"""
2+
3+
"""
4+
DFS(graph G, start vertex s):
5+
// all nodes initially unexplored
6+
mark s as explored
7+
for every edge (s, v):
8+
if v unexplored:
9+
DFS(G, v)
10+
"""
11+
12+
13+
def dfs(graph, start):
14+
"""The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate that
15+
behaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iterator
16+
to the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll pop
17+
it off the stack."""
18+
explored, stack = set(), [start]
19+
explored.add(start)
20+
while stack:
21+
v = stack.pop() # the only difference from BFS is to pop last element here instead of first one
22+
for w in graph[v]:
23+
if w not in explored:
24+
explored.add(w)
25+
stack.append(w)
26+
return explored
27+
28+
29+
G = {'A': ['B', 'C'],
30+
'B': ['A', 'D', 'E'],
31+
'C': ['A', 'F'],
32+
'D': ['B'],
33+
'E': ['B', 'F'],
34+
'F': ['C', 'E']}
35+
36+
print(dfs(G, 'A'))

0 commit comments

Comments
(0)

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