深度优先搜索

  无论是深度优先搜索还是广度优先搜索,搜索的关键在于建立两个数组,一个数组记录节点路径——输出结果;另一个数组记录已走过的节点——不走回头路。

class Graph(object):
    def __init__(self, points_nums, is_directed):
        self.__points_nums = points_nums
        self.__adj = [[] for _ in range(points_nums)]
        self.__directed = is_directed

    def add_edge(self, point1, point2):
        self.__adj[point1].append(point2)
        self.__in_degree[point2] += 1
        if not self.__directed:
            self.__adj[point2].append(point1)

    def get_adj(self, point):
        return self.__adj[point]

    def get_point_nums(self):
        return self.__points_nums


class DepthFirstPaths(object):
    def __init__(self, graph, start):
        self.__graph = graph
        self.__start = start
        self.__marked = [False for _ in range(graph.get_point_nums())]
        self.__edge_to = [None for _ in range(graph.get_point_nums())]
        self.__dfs(start)

    def __dfs(self, point):
        self.__marked[point] = True
        for w in self.__graph.get_adj(point):
            if not self.__mark[adj_point]:
                self.__edge_to[adj_point] = point
                self.__dfs(adj_point)

你可能感兴趣的:(算法与数据结构,#,深度优先搜索)