This article mainly introduces the implementation method of the python data structure graph. The example analyzes the Representation Method of the Python graph and the implementation skills of common pathfinding algorithms, for more information about how to implement the python data structure diagram, see the example in this article. Share it with you for your reference. The details are as follows:
The following is a brief introduction:
For example, there is a picture:
A-> B
A-> C
B-> C
B-> D
C-> D
D-> C
E-> F
F-> C
It can be built using a dictionary and a list.
graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']}
Find a path:
def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if not graph.has_key(start): return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None
Find all paths:
def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] if not graph.has_key(start): return [] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths
Find the Shortest Path:
def find_shortest_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if not graph.has_key(start): return None shortest = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph, node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest
I hope this article will help you with Python programming.