Skip to content

Instantly share code, notes, and snippets.

@thecodearrow
Created July 17, 2018 22:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thecodearrow/dfbb49affb2cf9bfc799fd63adbc6c98 to your computer and use it in GitHub Desktop.
Save thecodearrow/dfbb49affb2cf9bfc799fd63adbc6c98 to your computer and use it in GitHub Desktop.
from collections import defaultdict
class Graph:
def __init__(self):
self.neighbours=defaultdict(list)
def addEdge(self,u,v):
self.neighbours[u].append(v)
self.neighbours[v].append(u)
def bfs(self,i, n):
level = [-1] * (n+1)
queue = []
level[i] = 0
queue.append(i)
while queue:
head=queue.pop(0)
for k in self.neighbours[head]:
if level[k] == -1:
level[k] = 1 + level[head]
queue.append(k)
return level
q = int(input())
for case in range(q):
e = input().split()
n = int(e[0])
m = int(e[1])
g=Graph()
for edge in range(m):
e = input().split()
u = int(e[0])
v = int(e[1])
g.addEdge(u,v)
s = int(input())
distance = g.bfs(s, n)
dist = []
for i in distance[1:]:
if i > 0:
dist.append(str(i*6))
if i < 0:
dist.append(str(-1))
print(" ".join(dist))
#print("")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment