Question
This a C++ program. I want use 2-d array to write a program about Towers of Hanoi. Please show me the complete code. First, you
This a C++ program. I want use 2-d array to write a program about Towers of Hanoi.
Please show me the complete code.
First, you can implement your design using a static 2-D array with 3 columns for the3 posts, and you can initialize the array with the numbers 1, 2, and 3 in the first columnto represent the initial state of the game. The goal is to print out the board after eachmove in the game, seeing the following output. Example with two disks and a 2 x 3 board, i.e. call to towers(2, b, 1, 2, 3);
1 0 0
2 0 0
----------
0 0 0
2 0 1
----------
0 0 0
0 2 1
----------
0 1 0
0 2 0
----------
Here is an outline of the recursive towers function:
void towers(int disks, int b[][COLS], int from_col, int to_col, int spare)
If(number of disks is >= 1)
Call Towers with (disks-1, b, from_col, spare, to_col)
Move the disk
Print the board
Call Towers with (disks-1, b, spare, to_col, from_col)
Since this algorithm works for any n, then lets make our array dynamic. You will alwayshave 3 columns, but you will now prompt the user for the number of rows. You willdynamically create a 2-d array for the Towers function to use. Write a function calledcreate_array(). This function will take the number of rows as input and return a 2-darray on the heap: int ** create_array(int rows); This function needs to create the rows and columns on the heap, but in order to do this,you have to create the row pointers and then each row with a specific number ofcolumns. Here is how you would create the dynamic 2-d array for towers:
int **b; //a 2-d array is type
**b=new int[rows]; //create row pointers//for each row pointer create the row with 3 cols
for(int i=0; i b[i]=new int[3]; //create the row with 3 cols Now, change towers() to work with a dynamic 2-d array, which is int **b parameterinstead of int b[][COLS]. Get towers working with n disks using a n X 3 board.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started