深度优先搜索 - 算法讲解

🧑‍💻 算法学习 · Depth-First Search (DFS)

深度优先搜索 (Depth-First Search (DFS))

概述

难度:中等 (Medium)
分类:Graph Traversal / 图遍历

深度优先搜索是一种Graph/树遍历算法,沿着一条路径走到底,然后回溯探索其他路径。

DFS is a graph/tree traversal algorithm that explores as far as possible along each branch before backtracking.


算法原理

中文:从起点开始,尽可能深地访问节点,直到没有未访问的邻居,然后回溯。

English: Start from the source, visit nodes as deep as possible, until no unvisited neighbors, then backtrack.


复杂度分析

类型 复杂度
时间复杂度 O(V + E)
空间复杂度 O(V)

代码实现

def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    print(start, end=' ')
    for neighbor in graph[start]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited)
    return visited

每日练习

  1. 完成算法实现
  2. 分析算法复杂度
  3. 思考:算法的适用场景和局限性

相关阅读:算法专栏


💡 学习建议:算法学习重在理解思想,多写多练是关键。 💡 Learning tip: Algorithm learning is about understanding the core idea. Practice makes perfect.