Help Material
Help Material
/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 6 19:53:58 2021
@author: administator
"""
#This is the same code + code for shortest path function takes value of nodes from
user and find the path and shortest path
graph = {'A':['B','C'],
'B':['C','D'],
'C':['D'],
'D':['E','C'],
'E':['F'],
'F':[]}
#printing our graph
print(graph)
#to find simple path from and to given nodes
def pathFinder (graph,start,end,path=[]):
path = path+[start]
if start == end:
return path
if start not in graph:
return None
if end not in graph:
return None
for node in graph[start]:
newpath = pathFinder(graph, node, end, path)
if newpath != 'null':
return newpath
return None
#to find shortest path from and to given nodes
def shortestPathFinder(graph,start,end,path=[]):
path = path+[start]
if start == end:
return path
if start not in graph:
return None
if end not in graph:
return None
shortest = None
for node in graph[start]:
if node not in path:
newpath = shortestPathFinder(graph, node, end, path)
print("inloop")
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
start = input("Enter the start node: ")
end = input("Enter the end node: ")
print("path is : ",pathFinder(graph, start, end))
print("shortest path is : ",shortestPathFinder(graph, start, end))