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