resolve the tower o hanoi problem in php

The Tower of Hanoi problem is a classic computer science problem that is commonly used to introduce recursive thinking. The problem involves moving a stack of disks from one peg to another, while adhering to the following constraints:

  • Only one disk can be moved at a time
  • A larger disk cannot be placed on top of a smaller disk

We can solve this problem using a recursive algorithm as following:

main.php
function tower_of_hanoi($n, $source, $destination, $helper) {
    if ($n > 0) {
        // move top n-1 disks from source to helper peg
        tower_of_hanoi($n-1, $source, $helper, $destination);
 
        // move nth disk from source to destination peg
        echo "Move disk $n from $source to $destination\n";
 
        // move remaining n-1 disks from helper to destination peg
        tower_of_hanoi($n-1, $helper, $destination, $source);
    }
}

// Example usage
tower_of_hanoi(3, 'A', 'C', 'B');
507 chars
16 lines

In the example usage above, we are attempting to move 3 disks from peg A to peg C, using peg B as a helper. The output of this function would be:

main.php
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
168 chars
8 lines

This solution demonstrates how we can use recursion to break down the problem into smaller sub-problems, and solve them one-by-one until the entire problem is solved.

gistlibby LogSnag