-
Notifications
You must be signed in to change notification settings - Fork 2
/
graph_shortest_search.py
executable file
·69 lines (49 loc) · 1.5 KB
/
graph_shortest_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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/python
from modules.data_structures.Graph import Graph
from modules.data_structures.Queue import Queue
def bfs(g,start):
start.setDistance(0)
start.setPred(None)
vertQueue = Queue()
vertQueue.enqueue(start)
while (vertQueue.size() > 0):
currentVert = vertQueue.dequeue()
for nbr in currentVert.getConnections():
if (nbr.getColor() == 'white'):
nbr.setColor('gray')
nbr.setDistance(currentVert.getDistance() + 6)
nbr.setPred(currentVert)
vertQueue.enqueue(nbr)
currentVert.setColor('black')
def traverse(y, action="print"):
length = -1
x = y
while (x.getPred()):
if action == 'print': print(x.getId())
elif action == 'count': length += x.getDistance()
x = x.getPred()
if action == 'print':
print(x.getId())
elif action == 'count':
length += x.getDistance()
return length
T = int(raw_input().strip())
for t in xrange(T):
N,M = map(int, raw_input().strip().split())
g=Graph()
for i in xrange(N):
g.addVertex(i)
for i in xrange(M):
x,y = map(int, raw_input().strip().split())
g.addEdge(x-1, y-1, 6)
g.addEdge(y-1, x-1, 6)
S = int(raw_input().strip())-1
bfs(g,g.getVertex(S))
for i in xrange(N):
if S == i: continue
dist = g.getVertex(i).getDistance()
if dist == 0:
print -1,
else:
print dist,
print