Program:
import java.io.*;
class han
{
public void phanoi(int n,int source,int temp,int destn)
{
if(n>0)
{
phanoi(n-1,source,destn,temp);
System.out.println("move top disk from "+source+" to "+destn);
phanoi(n-1,temp,source,destn);
}
}
}
class hanoi
{
public static void main (String arg[]) throws IOException
{
DataInputStream x=new DataInputStream(System.in);
System.out.print("enter no of disks: ");
int n=Integer.parseInt(x.readLine());
han ob=new han();
ob.phanoi(n,1,2,3);
}
}
Output:
nn@ubuntu:~$ javac hanoi.java
nn@ubuntu:~$ java hanoi
enter no of disks:3
move top disk from 1 to 3
move top disk from 1 to 2
move top disk from 3 to 2
move top disk from 1 to 3
move top disk from 2 to 1
move top disk from 2 to 3
move top disk from 1 to 3
nn@ubuntu:~$
import java.io.*;
class han
{
public void phanoi(int n,int source,int temp,int destn)
{
if(n>0)
{
phanoi(n-1,source,destn,temp);
System.out.println("move top disk from "+source+" to "+destn);
phanoi(n-1,temp,source,destn);
}
}
}
class hanoi
{
public static void main (String arg[]) throws IOException
{
DataInputStream x=new DataInputStream(System.in);
System.out.print("enter no of disks: ");
int n=Integer.parseInt(x.readLine());
han ob=new han();
ob.phanoi(n,1,2,3);
}
}
Output:
nn@ubuntu:~$ javac hanoi.java
nn@ubuntu:~$ java hanoi
enter no of disks:3
move top disk from 1 to 3
move top disk from 1 to 2
move top disk from 3 to 2
move top disk from 1 to 3
move top disk from 2 to 1
move top disk from 2 to 3
move top disk from 1 to 3
nn@ubuntu:~$
0 comments:
Post a Comment