Lesson 8 +25 XP

Recursion, Backtracking & Tower of Hanoi

Recursion, Backtracking & Tower of Hanoi

Recursion is a problem-solving technique where a function solves a problem by calling itself on smaller subproblems until reaching a base case. Internally, every call pushes an Activation Record (Stack Frame) - containing return address, parameters, and local variables-onto the system call stack.

1. Types of Recursion & Recursion vs Iteration

  • Direct vs Indirect: Function calls itself directly vs A → B → A.
  • Tail Recursion: The recursive call is the very last operation (no pending work after return-compilers can optimize it into a O(1)-space loop!).
  • Tree Recursion: Makes multiple recursive calls per invocation (e.g., Fibonacci, Tower of Hanoi, Tree Traversals).
AspectRecursionIteration
MechanismFunction calls itself (Call Stack)Loop (for, while)
TerminationBase case reachedLoop condition becomes false
Space OverheadO(depth) stack framesO(1) extra space
Best Use CaseTrees, Graphs, Divide & Conquer, BacktrackingSimple linear scans, accumulators

2. Tower of Hanoi

Move N disks from Source (S) to Destination (D) using Auxiliary (A), never placing a larger disk onto a smaller disk:

C
void towerOfHanoi(int n, char S, char A, char D) {
    if (n == 1) {
        printf("Move disk 1 from %c to %c\n", S, D);
        return;
    }
    towerOfHanoi(n - 1, S, D, A);
    printf("Move disk %d from %c to %c\n", n, S, D);
    towerOfHanoi(n - 1, A, S, D);
}
  • Recurrence: T(n) = 2T(n - 1) + 1, T(1) = 1 ⇒ 2N - 1 moves (N = 3 ⇒ 7, N = 4 ⇒ 15).
  • Trace for N = 3 (S=A, A=B, D=C): A→C, A→B, C→B, A→C, B→A, B→C, A→C (7 moves).
  • Time Complexity: O(2N) | Stack Space: O(N).

3. Backtracking (N-Queens Problem)

Backtracking systematically builds a solution one decision at a time in a state-space tree and prunes (abandons) any partial branch the moment it violates a constraint-undoing the last choice and trying the next option.

N-Queens Safety & Trace

Goal: Place N queens on an N × N chessboard so no two queens share the same row, column, or diagonal.

  1. Place exactly one queen per row (row = 0 .. N-1).
  2. For candidate (row, col), verify no earlier queen at (r, c) conflicts:
  • Same column: c == col
  • Same diagonal: abs(r - row) == abs(c - col)
  1. If safe, place queen and recurse to row + 1. If no column in row works, backtrack to row - 1 and move its queen to the next column!
  • 4-Queens Solution: Columns [1, 3, 0, 2] (0-indexed) - (0,1), (1,3), (2,0), (3,2).
C
int isSafe(int board[], int row, int col) {
    for (int r = 0; r < row; r++) {
        if (board[r] == col || abs(r - row) == abs(board[r] - col))
            return 0;
    }
    return 1;
}

Tower of Hanoi with N = 4: The Recursive Call Tree TOWER(N, FROM, VIA, TO):

  1. If N = 1: move disk 1 FROM → TO; return.
  2. TOWER(N − 1, FROM, TO, VIA) - park the top N−1 disks on VIA.
  3. Move disk N FROM → TO.
  4. TOWER(N − 1, VIA, FROM, TO) - bring the N−1 disks onto TO.

For N = 4 with pegs A (source), B (spare), C (destination):

TEXT
TOWER(4, A, B, C)
├─ TOWER(3, A, C, B)
│  ├─ TOWER(2, A, B, C)  → A→B, A→C, B→C
│  ├─ move 3: A→B
│  └─ TOWER(2, C, A, B)  → C→A, C→B, A→B
├─ move 4: A→C
└─ TOWER(3, B, A, C)
   ├─ TOWER(2, B, C, A)  → B→C, B→A, C→A
   ├─ move 3: B→C
   └─ TOWER(2, A, B, C)  → A→B, A→C, B→C

The full move sequence (15 moves = 2⁴ − 1):

No.MoveNo.MoveNo.Move
1A→B6C→B11C→A
2A→C7A→B12B→C
3B→C8A→C (disk 4)13A→B
4A→B9B→C14A→C
5C→A10B→A15B→C

The recurrence T(n) = 2T(n-1) + 1, T(1) = 1 gives T(n) = 2n - 1, so the algorithm is O(2n); the recursion depth (stack space) is only O(n).

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Differentiate between Recursion and Iteration. Write a recursive C function for Tower of Hanoi and trace it for N = 3 disks. (7.5 Marks)
  • Write: Comparison table (stack vs loop, space, termination), towerOfHanoi() C code, T(n) = 2N - 1 derivation, and the 7-move trace.
  • Q2. What is Backtracking? Explain how the N-Queens problem is solved using Backtracking. (5 Marks)
  • Write: State-space tree + constraint pruning, row-by-row placement, isSafe() column/diagonal check, and the 4-Queens solution [1, 3, 0, 2].