数据结构-图
Posted pfeiliu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构-图相关的知识,希望对你有一定的参考价值。
有向图
# -*- coding:utf-8 -*- def searchGraph(graph, start, end): results = [] generatePath(graph, [start], end, results) results.sort(key=lambda x:len(x))#按元素长度升序排序 return results def generatePath(graph, path, end, results): state = path[-1] if state == end: results.append(path) else: for arc in graph[state]: if arc not in path: generatePath(graph, path + [arc], end, results) if __name__ == ‘__main__‘: Graph = {‘A‘: [‘B‘, ‘C‘, ‘D‘], ‘B‘: [‘E‘], ‘C‘: [‘D‘, ‘F‘], ‘D‘: [‘B‘, ‘E‘, ‘G‘], ‘E‘: [], ‘F‘: [‘D‘, ‘G‘], ‘G‘: [‘E‘]} r = searchGraph(Graph, ‘A‘,‘D‘) print(‘************************‘) print(‘ path A to D‘) print(‘************************‘) for i in r: print(i) r = searchGraph(Graph, ‘A‘,‘E‘) print(‘************************‘) print(‘ path A to E‘) print(‘************************‘) for i in r: print(i) r = searchGraph(Graph, ‘C‘,‘E‘) print(‘************************‘) print(‘ path C to E‘) print(‘************************‘) for i in r: print(i)
************************ path A to D ************************ [‘A‘, ‘D‘] [‘A‘, ‘C‘, ‘D‘] [‘A‘, ‘C‘, ‘F‘, ‘D‘] ************************ path A to E ************************ [‘A‘, ‘B‘, ‘E‘] [‘A‘, ‘D‘, ‘E‘] [‘A‘, ‘C‘, ‘D‘, ‘E‘] [‘A‘, ‘D‘, ‘B‘, ‘E‘] [‘A‘, ‘D‘, ‘G‘, ‘E‘] [‘A‘, ‘C‘, ‘D‘, ‘B‘, ‘E‘] [‘A‘, ‘C‘, ‘D‘, ‘G‘, ‘E‘] [‘A‘, ‘C‘, ‘F‘, ‘D‘, ‘E‘] [‘A‘, ‘C‘, ‘F‘, ‘G‘, ‘E‘] [‘A‘, ‘C‘, ‘F‘, ‘D‘, ‘B‘, ‘E‘] [‘A‘, ‘C‘, ‘F‘, ‘D‘, ‘G‘, ‘E‘] ************************ path C to E ************************ [‘C‘, ‘D‘, ‘E‘] [‘C‘, ‘D‘, ‘B‘, ‘E‘] [‘C‘, ‘D‘, ‘G‘, ‘E‘] [‘C‘, ‘F‘, ‘D‘, ‘E‘] [‘C‘, ‘F‘, ‘G‘, ‘E‘] [‘C‘, ‘F‘, ‘D‘, ‘B‘, ‘E‘] [‘C‘, ‘F‘, ‘D‘, ‘G‘, ‘E‘]
以上是关于数据结构-图的主要内容,如果未能解决你的问题,请参考以下文章