Leetcode Tag Search | Back

DFS template

Category: /template

DFS - Template I: recursive

Explaination Details Template Index
def DFS(Node cur, Node target, Set<Node> visited):
    return True if cur is target
    for next in each_neighbor_of_cur:
        if next not in visited:
            add next to visted
            return true if DFS(next, target, visited)
    return False
}

DFS - Template II: iteration

def DFS(root, target):
    Set<Node> visited = set()
    stack = collections.deque()
    stack.append(root)
    while s is not empty:
        Node cur = stack.pop()
        if cur is target: return result 
        for next in cur.neighbors:
            if next not in visited: 
                visited.add(next)
                stack.append(next)
    return result

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)