Skip to content

Instantly share code, notes, and snippets.

@mridul111998
Created March 4, 2019 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mridul111998/c24fbdb46492b57f7f17decd8802eac2 to your computer and use it in GitHub Desktop.
Save mridul111998/c24fbdb46492b57f7f17decd8802eac2 to your computer and use it in GitHub Desktop.
# this code prints all the shortest paths possible from start node
# to end node in UNDIRECTED, UNWEIGHTED graph
class node:
def __init__(self,val,path,dis):
self.val = val
self.path = path
self.dis = dis
ans = []
graph =[
[0, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 1],
[0, 1, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 0, 0]]
n = len(graph)
distance = [float('inf')]*n # n is number of nodes
end = 6
queue = []
start = 0
queue.append(node(start,[start],0))
min_dis = float('inf')
distance[start]=0
while(queue):
s = queue.pop(0)
if(s.val==end):
min_dis = s.dis
ans.append(s)
if(s.dis>min_dis):
pass
else:
for i in range(n):
if(graph[s.val][i]==1 and distance[i]>=s.dis+1):
queue.append(node(i,s.path+[i],s.dis+1))
distance[i] = s.dis+1
for i in ans:
print i.path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment