Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

def start_graph(filePath):

graph = {}
with open(filePath, "r") as file:
line = file.readline()
while line:
codePart = line.strip().split()
node = codePart[0]
max_value = int(codePart[1])
neighbors = {}
i=2
while i < len(codePart):
neighbor = codePart[i]
dist = int(codePart[i + 1])
neighbors[neighbor] = dist
i += 2
graph[node] = {"max_value": max_value, "neighbors": neighbors}
line = file.readline()
return graph

def algo_search(graph, start_node, end_node):


from queue import PriorityQueue

readQueue = PriorityQueue()
readQueue.put((graph[start_node]["max_value"], 0, start_node, [start_node]))

visited = set()

max_iterations = 1000

for _ in range(max_iterations):
if readQueue.empty():
break

estimated_cost, current_cost, current_node, path = readQueue.get()

if current_node == end_node:
return path, current_cost

if current_node in visited:
continue

visited.add(current_node)
for neighbor, distance in graph[current_node]["neighbors"].items():
if neighbor not in visited:
total_cost = current_cost + distance
estimated_total_cost = total_cost + graph[neighbor]["max_value"]
readQueue.put((estimated_total_cost, total_cost, neighbor, path + [neighbor]))

return None, None

def main():
filePath = "20301096_Rida Mahmud
Sadman_CSE422_02_Assignment01_summer2024_InputFile.txt"
graph = start_graph(filePath)

start_node = input("Start node: ").strip()


end_node = input("Destination: ").strip()

if start_node not in graph:


print(f"Start node '{start_node}' does not exist on graph.")
return
if end_node not in graph:
print(f"Destination node '{end_node}' does not exit on graph.")
return

path, total_distance = algo_search(graph, start_node, end_node)

if path is not None:


print("Path:", " -> ".join(path))
print("Total distance:", total_distance, "km")
else:
print("NO PATH FOUND")

if __name__ == "__main__":
main()

You might also like