Skip to content

Commit 700dae1

Browse files
authored
Merge pull request thuva4#257 from bugov/master
DepthFirstSearch in Python thuva4#248
2 parents d3fc5f8 + c42bf17 commit 700dae1

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/env python3
2+
# Naive recursive implementation of DFS on ordered graphs
3+
from collections import defaultdict
4+
import sys
5+
6+
7+
def dfs(node, adjacency_lists, strategy, visited=None):
8+
if not visited:
9+
visited = set()
10+
11+
visited.add(node)
12+
strategy(node)
13+
14+
for adj_node in adjacency_lists[node]:
15+
if adj_node in visited:
16+
continue
17+
18+
dfs(adj_node, adjacency_lists, strategy, visited)
19+
20+
21+
if __name__ == '__main__':
22+
start_from = next(sys.stdin).strip()
23+
adjacency = defaultdict(list)
24+
25+
for line in sys.stdin:
26+
line = line.strip()
27+
28+
if not line:
29+
continue
30+
31+
from_, to = line.split()
32+
adjacency[from_].append(to)
33+
34+
dfs(start_from, adjacency, lambda x: print(x))
35+

DepthFirstSearch/Python/in.txt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
0
2+
0 1
3+
0 6
4+
0 8
5+
1 4
6+
1 6
7+
1 9
8+
2 4
9+
2 6
10+
3 4
11+
3 5
12+
3 8
13+
4 5
14+
4 9
15+
7 8
16+
7 9
17+

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Borwein's Algorithm | :+1: | | | | :+1: | | | | ||
1717
BubbleSort | :+1: | :+1: | :+1: | :+1: | :+1: | :+1: | | :+1: | :+1: |
1818
Conjugate Gradient | | | | | :+1: | | | | ||
1919
CountingSort | :+1: | :+1: | | | :+1: | | | | |
20-
DepthFirstSearch | :+1: | | | | :+1: | | | | |
20+
DepthFirstSearch | :+1: | :+1: | | | :+1: | | | | |
2121
Dijkstra's | :+1: | :+1: | | | :+1: | | | | |
2222
Doomsday | :+1: | :+1: | | | | :+1: | | | | :+1: | :+1:
2323
ElevatorAlgorithm | :+1: | | | | | | | |

0 commit comments

Comments
 (0)