VB.Net program to implement the Tower of Hanoi problem

Here, we are going to learn how to implement the Tower of Hanoi problem in VB.Net?
Submitted by Nidhi, on January 18, 2021 [Last updated : March 08, 2023]

Implementation of Tower of Hanoi in VB.Net

Here, we will implement the Tower of Hanoi problem using recursion.

Program/Source Code:

The source code to implement the Tower of Hanoi problem is given below. The given program is compiled and executed successfully.

VB.Net code to implement the Tower of Hanoi problem

'VB.Net program to implement the Tower of Hanoi problem.

Imports System

Module Module1
    Class TOH
        Private discs As Integer

        Public Sub New(ByVal val As Integer)
            discs = val
        End Sub

        Public Sub MoveDiscs(ByVal num As Integer, ByVal from As Integer, ByVal tto As Integer, ByVal other As Integer)
            If (num > 0) Then
                MoveDiscs(num - 1, from, other, tto)
                Console.WriteLine("Move disk {0} from tower {1} to tower {2}", num, from, tto)
                MoveDiscs(num - 1, other, tto, from)
            End If
        End Sub
    End Class

    Sub Main()
        Dim T As TOH
        Dim total_discs As Integer

        Console.Write("Enter the total number of discs: ")
        total_discs = Integer.Parse(Console.ReadLine())

        T = New TOH(total_discs)
        T.MoveDiscs(total_discs, 1, 3, 2)
    End Sub
End Module

Output

Enter the total number of discs: 3
Move disk 1 from tower 1 to tower 3
Move disk 2 from tower 1 to tower 2
Move disk 1 from tower 3 to tower 2
Move disk 3 from tower 1 to tower 3
Move disk 1 from tower 2 to tower 1
Move disk 2 from tower 2 to tower 3
Move disk 1 from tower 1 to tower 3
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contains TOH class and Main() function.

The TOH class contains a parameterized constructor and MoveDiscs() method. Here, parameterized constructor is used to initialized with the number of discs. The MoveDiscs() method is a recursive method, which is used to move the disc according to the Tower of Hanoi problem.

The Main() function is the entry point for the program, Here, we created the object of TOH class and read the number of discs from the user, and print discs movement on the console screen.

VB.Net Data Structure Programs »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.