Dfs

DFS

深度优化搜索

简介

目标:图的系统化搜索,模仿迷宫探索式搜索

应用:

  • 根据一个点,找到所有关联的点
  • 判断两个点之间是否可达

alt

两点之间搜索路径不唯一

代码

class DFS:
    def __init__(self, graph: Graph, source: int):
        self.marked = [False] * graph.v
        self.edge_to = [i for i in range(graph.v)]
        self.source = source
        self.graph = graph
        self.cnt = 0
        self.__validate_v(source)
        self.__dfs(graph, source)

    def __validate_v(self, v):
        if v < 0 or v >= self.graph.v:
            raise Exception("{} illegal".format(v))

    def __dfs(self, graph, v):
        self.marked[v] = True
        self.cnt += 1
        for w in graph.get_adj(v):
            if not self.marked[w]:
                self.edge_to[w] = v
                self.__dfs(graph, w)

    def has_path_to(self, v):
        self.__validate_v(v)
        return self.marked[v]

    def path_to(self, v):
        self.__validate_v(v)
        if not self.has_path_to(v):
            return None
        path = []
        x = v
        while x != self.source:
            path.append(x)
            x = self.edge_to[x]
        path.append(self.source)
        return path

    def count(self):
        return self.cnt

    def connected(self):
        return self.cnt == self.graph.v


采用栈记录搜索过程

说明:

  • marked,记录点是否被访问
  • edge_to,记录点首次被访问时的前一个点,根据父节点一路查找下去,可以匹配到搜索路径
  • cnt,记录与点有关联的点的个数,可用于判断图是否是全连接的