Skip to content

Instantly share code, notes, and snippets.

@Abdujabbar
Last active January 29, 2016 12:27
Show Gist options
  • Save Abdujabbar/f4c3e6bd36615930e8f8 to your computer and use it in GitHub Desktop.
Save Abdujabbar/f4c3e6bd36615930e8f8 to your computer and use it in GitHub Desktop.
BFS
def bfs(g, start):
distance = [0] * len(g)
queue = []
queue.append(start - 1)
distance[start - 1] = 0
while len(queue) != 0:
current = queue.pop(0)
for i in g[current]:
if distance[i] == 0:
distance[i] = distance[current] + 6
queue.append(i)
return distance
t = int(input())
for i in range(t):
v, e = input().split()
GRAPH = {}
for i in range(int(v)):
GRAPH[i] = set()
for j in range(int(e)):
u, q = [int(x) for x in input().split()]
GRAPH[u - 1].add(q - 1)
start = int(input())
visited = bfs(GRAPH, start)
for j in range(len(visited)):
if j == start - 1:
continue
if visited[j] == 0:
print("-1", end=' ')
else:
print(visited[j], end=' ')
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment