-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfssearchpath.py
More file actions
82 lines (71 loc) · 1.94 KB
/
bfssearchpath.py
File metadata and controls
82 lines (71 loc) · 1.94 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import sys
from collections import deque
file_name = sys.argv[1]
name1 = sys.argv[2]
name2 = sys.argv[3]
def bfs_dist(graph, start, end):
flag = 0
vertices = deque([start])
visited = set([start])
distances = {x : -1 for x in graph.keys()}
while vertices:
vertex = vertices.popleft()
if vertex == start:
distances[vertex] = 0
for neighbor in graph[vertex]:
if neighbor not in visited:
distances[neighbor] = distances[vertex] + 1
visited.add(neighbor)
vertices.append(neighbor)
if end in vertices:
break
if end in vertices:
print(f"Distance: {distances[end]}")
else:
print("No connection")
flag = 1
return flag
def search_path(graph, start, end):
vertices = deque([(start,[start])])
visited = set([start])
while vertices:
vertex, path = vertices.popleft()
for neighbor in graph[vertex]:
if neighbor == end:
return path + [end]
else:
if neighbor not in visited:
visited.add(neighbor)
vertices.append((neighbor, path + [neighbor]))
actors = {}
movies = {}
f = open(file_name, "r", encoding='utf8')
while True:
s = f.readline().strip("\n")
if s == "":
break
else:
actor, movie = [x for x in s.split(" ")]
if actor not in actors:
actors[actor] = set([movie])
else:
actors[actor].add(movie)
if movie not in movies:
movies[movie] = set([actor])
else:
movies[movie].add(actor)
f.close()
graph = {}
for actor in actors:
tmp = set()
for movie in actors[actor]:
tmp.update(movies[movie])
graph[actor] = tmp - set([actor])
flag = bfs_dist(graph, name1, name2)
path = search_path(graph, name1, name2)
if flag == 0:
for i in range(len(path) - 1):
movie = set(actors[path[i]]) & set(actors[path[i+1]])
print(f"{path[i]} was with {path[i + 1]} in {movie}")
#python3 bfssearchpath.py "actors.tsv" "Kevin Bacon" "Tom Hanks"
#bfssearchpath.py "actors.tsv" "Kevin Bacon" "Tom Hardy"