python - dfs

fly00love 2020-05-10

解决方案:

class Gra(object):
    def __init__(self):
        self.order = []
        self.neighboor = {}
        self.visit = {}

    def _dfs_visit_(self, u):
        if u in self.neighboor:
            for v in self.neighboor[u]:
                print(v)
                if v not in self.visit:
                    self.visit[v] = True
                    self._dfs_visit_(v)
        self.visit[u] = True

    def add_node(self, node):
        k, v = node
        self.neighboor[k] = v

    def dfs(self):
        for u in self.neighboor.keys():
            if u not in self.visit:
                print(u)
                self._dfs_visit_(u)


g = Gra()
g.add_node((‘A‘, [‘B‘, ‘C‘]))
g.add_node((‘C‘, [‘F‘]))
g.add_node((‘B‘, [‘D‘, ‘E‘]))
g.add_node((‘F‘, [‘G‘, ‘H‘]))
g.dfs()

相关推荐

wangjunyi / 0评论 2012-06-27