DEV Community

Debesh P.
Debesh P.

Posted on

1 1 1 1 1

Tower Of Hanoi | GeeksforGeeks Beginner's DSA Sheet | Recursion | With Source Code

hola coders!

Welcome to my latest video, where I break down the Tower of Hanoi problem using the recursive approach in the simplest and most understandable way!

what is the Tower of Hanoi?

The Tower of Hanoi is a classic problem that involves moving a set of disks from one peg to another, following three simple rules:

  • Only one disk can be moved at a time.
  • A disk can only be placed on top of a larger disk.
  • You can only move disks between the three pegs.


Problem Link: https://www.geeksforgeeks.org/problems/tower-of-hanoi-1587115621/1

Source Code: https://github.com/debeshp6/Gfg-Tutorials/blob/main/TowerOfHanoi.java


Code

// User function Template for Java

class Solution {

    public int towerOfHanoi(int n, int from, int to, int aux) {
        // Your code here

        if(n == 0) return 0;

        int move1 = towerOfHanoi(n-1, from, aux, to); // recursive call 1
        int move2 = 1;
        int move3 = towerOfHanoi(n-1, aux, to, from); // recursive call 2

        return move1 + move2 + move3; // returning the total number of movements
    }
}
Enter fullscreen mode Exit fullscreen mode

This problem is an excellent example of recursion and divide-and-conquer techniques, making it essential for coding interviews and competitive programming.

why Recursion?

Instead of thinking about moving all disks at once, we break the problem into smaller subproblems, moving one disk at a time while following the rules. This recursive approach makes the solution clean, elegant, and easy to implement.

If you're preparing for coding interviews or learning DSA, understanding recursion is a must! The Tower of Hanoi is one of the best problems to get a grip on recursive problem-solving techniques.

Got any questions? Drop them in the comments below! I’ll be happy to help.

happy coding!

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️