def dfs(origin): # DFS from origin:
origin.visited = True # Mark the origin as visited
for neighbor in origin.neighbors: # Loop over the neighbors
if not neighbor.visited: dfs(neighbor) # Visit each neighbor if not already visited
如果将“已经访问过”的信息存储在单独的数据结构中:
def dfs(node, visited): # DFS from origin, with already-visited set:
visited.add(node) # Mark the origin as visited
for neighbor in node.neighbors: # Loop over the neighbors
if not neighbor in visited: # If the neighbor hasn't been visited yet,
dfs(neighbor, visited) # then visit the neighbor
dfs(origin, set())
深度优先搜索(deep First Search, DFS)算法,顾名思义,是通过最近发现的节点x的外缘发现其未访问的邻居。如果节点x没有未访问的邻居,算法将回溯到发现节点x的节点的未访问邻居(通过其外边),依此类推,直到访问了从原始源可到达的所有节点(如果还有剩余的未访问节点,则可以继续获取另一个原始源,依此类推)。