-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathdepth_first_search.py
53 lines (43 loc) · 1.23 KB
/
depth_first_search.py
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
"""
Execution: python depth_first_search.py filename.txt s
Data files: https: // algs4.cs.princeton.edu / 41graph / tinyG.txt
https: // algs4.cs.princeton.edu / 41graph / mediumG.txt
Run depth first search on an undirected graph.
Runs in O(E + V) time.
% python depth_first_search.py tinyG.txt 0
0 1 2 3 4 5 6
NOT connected
% python depth_first_search.py tinyG.txt 9
9 10 11 12
NOT connected
"""
from algs4.graph import Graph
class DepthFirstSearch:
def __init__(self, G, s):
self.marked = [False for _ in range(G.V)]
self.count = 0
self.dfs(G, s)
def dfs(self, G, v):
self.marked[v] = True
self.count += 1
for w in G.adj[v]:
if not self.marked[w]:
self.dfs(G, w)
if __name__ == '__main__':
import sys
f = open(sys.argv[1])
s = int(sys.argv[2])
V = int(f.readline())
E = int(f.readline())
g = Graph(V)
for i in range(E):
v, w = f.readline().split()
g.add_edge(v, w)
search = DepthFirstSearch(g, s)
for v in range(g.V):
if search.marked[v]:
print(str(v) + " ")
if search.count == g.V:
print("connected")
else:
print("not connected")