美文网首页Python设计模式
Python设计模式 - 图搜索模式

Python设计模式 - 图搜索模式

作者: jumo | 来源:发表于2020-02-21 10:54 被阅读0次

class GraphSearch:

    """

    在python模拟图搜索模式

    """

    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

#图用法的例子

graph = {'A': ['B', 'C'],

         'B': ['C', 'D'],

         'C': ['D'],

         'D': ['C'],

         'E': ['F'],

         'F': ['C']

         }

#新的图形搜索对象的初始化

graph1 = GraphSearch(graph)

print(graph1.find_path('A', 'D'))

print(graph1.find_all_path('A', 'D'))

print(graph1.find_shortest_path('A', 'D'))

相关文章

  • Python设计模式 - 图搜索模式

    classGraphSearch: """ 在python模拟图搜索模式 """ def__init__(self...

  • 二十三种设计模式及其python实现

    参考文献: 《大话设计模式》——吴强 《Python设计模式》——pythontip.com 《23种设计模式》—...

  • UML 类图中的结构及 python 实现

    Reference python设计模式-UML类图中的结构及python实现看懂UML类图和时序图faif/py...

  • 基础-单例模式

    单例模式总结-Python实现 面试里每次问设计模式,必问单例模式 来自《Python设计模式》(第2版) 1.理...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 设计模式总结大纲

    设计模式范例 设计模式 基本的UML类图的关系 设计模式之(命令模式) 基本概念 角色划分 UML类图 应用场景 ...

  • Swift设计模式-目录

    推荐图书:《Head First设计模式》《大话设计模式》《设计模式之禅》, 设计模式思维导图 图形说明一切: 设...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 《精通Python设计模式_带索引书签目录》 分享下载

    书籍信息 书名: 精通Python设计模式_带索引书签目录 标签: 精通Python设计模式_带索引书签目录,免费...

网友评论

    本文标题:Python设计模式 - 图搜索模式

    本文链接:https://www.haomeiwen.com/subject/soaqqhtx.html