W pythonie:
from collections import deque
graph = [
['a', 'b', 'c', 'd', 'e', 'f'],
['g', 'e', 'h', 'i', 'j'],
['k', 'l', 'i', 'n', 'm']
]
def graph_nodes(a_graph):
return list(set([node for _ in a_graph for node in _]))
def neighbours(a_graph, a_node):
node_neighbours = []
"""
Przegladamy kazda z list reprezentujacych graf i jesli napotkamy zadany wierzcholek, to zapamietujemy jego
poprzednika i nastepnika (o ile istnieja).
"""
for a_list in a_graph:
for i, element in enumerate(a_list):
if element == a_node and i + 1 < len(a_list):
node_neighbours.append(a_list[i + 1])
if element == a_node and i - 1 >= 0:
node_neighbours.append(a_list[i - 1])
return list(set(node_neighbours))
# Zwykle przechodzenie grafu
def find_path(a_graph, from_node, to_node):
nodes = graph_nodes(a_graph)
if from_node not in nodes or to_node not in nodes:
return None
visited = {n: False for n in nodes}
""" W kolejce pamietamy sciezke od zadanego wierzcholka"""
queue = deque([from_node])
while len(queue) > 0:
remembered_path = queue.pop()
current_node = remembered_path[-1] # Ostatni element sciezki to wierzcholek do dalszej analizy
visited[current_node] = True
if current_node == to_node:
return remembered_path
for node in neighbours(a_graph, current_node):
if not visited[node]:
visited[node] = True
new_path = [n for n in remembered_path]
new_path.append(node)
queue.append(new_path)
return None
print("Path={}".format(find_path(graph, 'd', 'n')))
print("Path={}".format(find_path(graph, 'a', 'm')))
print("Path={}".format(find_path(graph, 'k', 'j')))
print("Path={}".format(find_path(graph, 'FOO', 'BAR')))
print("Path={}".format(find_path(graph, 'a', 'BAR')))
https://ideone.com/mQObpQ