Python版

https://github.com/faif/python-patterns/blob/master/other/graph_search.py

#!/usr/bin/env python
# -*- coding: utf-8 -*- "" class GraphSearch: """Graph search emulation in python, from source
http://www.python.org/doc/essays/graphs/""" def __init__(self, graph):
self.graph = graph def find_path(self, start, end, path=None):
path = path or [] path.append(start)
if start == end:
return path
for node in self.graph.get(start, []):
if node not in path:
newpath = self.find_path(node, end, path[:])
if newpath:
return newpath def find_all_path(self, start, end, path=None):
path = path or []
path.append(start)
if start == end:
return [path]
paths = []
for node in self.graph.get(start, []):
if node not in path:
newpaths = self.find_all_path(node, end, path[:])
paths.extend(newpaths)
return paths def find_shortest_path(self, start, end, path=None):
path = path or []
path.append(start) if start == end:
return path
shortest = None
for node in self.graph.get(start, []):
if node not in path:
newpath = self.find_shortest_path(node, end, path[:])
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest # example of graph usage
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']
} # initialization of new graph search object
graph1 = GraphSearch(graph) print(graph1.find_path('A', 'D'))
print(graph1.find_all_path('A', 'D'))
print(graph1.find_shortest_path('A', 'D')) ### OUTPUT ###
# ['A', 'B', 'C', 'D']
# [['A', 'B', 'C', 'D'], ['A', 'B', 'D'], ['A', 'C', 'D']]
# ['A', 'B', 'D']

Python转载版

最新文章

  1. ASP.NET Core 中间件详解及项目实战
  2. GPS部标平台的架构设计(十)-基于Asp.NET MVC构建GPS部标平台
  3. [转]MySQL Connector/C++(一)
  4. Android Service完全解析,关于服务你所需知道的一切(上)
  5. .Net Core CLI windows安装
  6. CentOS7 基础配置
  7. Labview实现幅度信号调制(AM)
  8. POJ 3233 Matrix Power Serie
  9. yiic创建YII应用 &quot;php.exe&quot;不是内部或外部命令 解决办法
  10. 【C++学习笔记1】
  11. [转载][NAS] 使用win8的“存储池”功能~
  12. Hadoop之——CentOS构造ssh否password登录注意事项
  13. mysql 分析第一步
  14. C# 实现语音听写
  15. new day
  16. android开发之this.finish()的使用
  17. cocos2D v3.4 在TileMap中开启高清显示
  18. [WDS] Warnings while compiling. vue 项目运行控制台输出太多警告信息
  19. AI外包 人工智能外包 长年承接人工智能项目 北京动点软件
  20. 深入浅出Tomcat系列

热门文章

  1. NAT &amp; 防火墙
  2. C++ substr 的两个用法
  3. 准备 dubbo 学习目录
  4. Django笔记&教程 2-4 视图常用
  5. SpringCloud升级之路2020.0.x版-35. 验证线程隔离正确性
  6. 菜鸡的Java笔记 图书馆
  7. vs2012换肤功能,vs2012主题及自定义主题
  8. [luogu7600]封闭道路
  9. [bzoj3329]Xorque
  10. 接上篇:Git Worktree 高级使用,这样清爽多了