DSA
    intermediate

    Depth-First Search (DFS)

    Software Engineer path · lesson 22 of 99
    time O(V + E)
    space O(V)

    Undirected, like A-B, B-C. Badges show discovery/finish times (DFS) or distance (BFS).

    Try:
    Start node
    Traversal

    Same graph, same start: compare the visit order.

    Neighbour order
    ABCDEF
    stack
    order
    CurrentNext to visitOn the stackFinishedBack edge (cycle)

    Depth-first from A: go as deep as possible, then backtrack.

    Code (running line highlighted)
    1. 1dfs(u):
    2. 2 visited.add(u); disc[u] = time++
    3. 3 for v in neighbours(u):
    4. 4 if v not visited: parent[v] = u; dfs(v) # tree edge
    5. 5 elif v != parent[u]: found a cycle # back edge
    6. 6 finish[u] = time++ # backtrack
    Visits
    0 / 6
    Edge checks
    0 / 12

    Tap any element in the diagram to inspect its state at this step.

    1 / 25

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Go deep first

    Sequence

    Graph: A → B, C · B → D, E · C → F. Visiting neighbours alphabetically, order the nodes as DFS from A visits them.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    6. 6Drop a step here
    6 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What data structure is implicitly used in recursive DFS?

    Write the code

    Runs your solution

    Number of Islands

    Return the number of islands in a 2D binary grid ("1" = land, "0" = water).

    Example Cases

    Input:[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
    Output:1
    Input:[["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
    Output:3
    javascript
    function numIslands(grid) {
      // Your code here
    }

    When to reach for this

    • Find **Connected Components**
    • Detect Cycles in a Graph
    • Maze solving / Path existence
    • Topological Sorting (DFS based)

    Interview Questions

    Amazon
    Meta
    Bloomberg
    Meta
    LinkedIn
    Microsoft
    Uber
    Google
    Airbnb
    Amazon
    LinkedIn
    Bloomberg
    Microsoft
    Netflix
    Google

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required