Files
CS412-Applied-Algorithms/Graph-Search/cs412_bus_stops_a.py

67 lines
1.4 KiB
Python

"""
name: Nicholas Tamassia
Honor Code and Acknowledgments:
This work complies with the JMU Honor Code.
Comments here on your code and submission.
"""
from collections import defaultdict, deque
def whatever_first_search(graph: dict[str, set[str]], start: str, stop: str):
bag: deque[tuple[str | None, str]] = deque()
bag.append((None, start))
visited: set[str] = set()
parent: dict[str, str | None] = {}
while len(bag) != 0:
parent_node, u = bag.pop()
if u in visited:
continue
visited.add(u)
parent[u] = parent_node
if u == stop:
path: list[str] = []
while u is not None:
path.append(u)
u = parent[u]
path.reverse()
return path
for v in graph[u]:
if v not in visited:
bag.append((u, v))
return None
# All modules for CS 412 must include a main method that allows it
# to imported and invoked from other python scripts
def main():
n: int = int(input())
graph: dict[str, set[str]] = defaultdict(set)
for _ in range(0, n):
u, v = input().split()
graph[u].add(v)
graph[v].add(u)
target = input().split()
path = whatever_first_search(graph, target[0], target[1])
if path is None:
print("no route possible")
else:
print(" ".join(path))
if __name__ == "__main__":
main()