-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.py
More file actions
39 lines (32 loc) · 792 Bytes
/
dfs.py
File metadata and controls
39 lines (32 loc) · 792 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
36
37
38
39
import sys
from collections import deque
file_name = sys.argv[1]
start_vert = sys.argv[2]
def dfs(graph, start, visited = 0):
if not visited:
visited = set([start])
else:
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited
graph = {}
f = open(file_name, "r", encoding="utf-8")
while True:
s = f.readline().strip("\n")
if s == "":
break
else:
city1 , city2 = [x for x in s.split("\t")]
if city1 not in graph:
graph[city1] = set([city2])
else:
graph[city1].add(city2)
if city2 not in graph:
graph[city2] = set([city1])
else:
graph[city2].add(city1)
f.close()
print(dfs(graph, start_vert))
#python3 dfs.py "cities.tsv" "Полоцк"