Python Data Structure Graph Implementation Method

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.