Create a path for a mouse to travel in a maze. Use a 2 dimensional array and sta
ID: 3762773 • Letter: C
Question
Create a path for a mouse to travel in a maze. Use a 2 dimensional array and start the mouse in location array[0][0]. The mouse must find its way to the opposite corner. Repeatedly get a random number representing one of 8 possible moves. A legal move is one that moves forward, and does not run into the edge of the array. If the move is illegal the poor mouse must starts over with location [0][0]. Going forward is defined as the sum of the two array indexes either increasing or staying the same. Count the number of times the mouse must start over before he finds a path from beginning to the end, and print the array to the screen showing the path that was successful. Allow the mouse to repeatedly run the maze and choose the size of the two dimensional array. Can someone help me in JAVA please
Explanation / Answer
// out of the 8 possible paths, there are 5 forward moves, which i numbered as 1 to 5.. It can be changed //according to convenience.. just the number in the case statements need to be changed
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void intialise(int** a, int rows, int columns)
{
for(int i = 0;i<rows;i++)
{
for(int j = 0; j<columns; j++)
a[i][j] = 0;
}
a[0][0] = 1;
}
int main() {
int rows,columns, i = 0, j = 0,count = 1;
bool flag = false;
cout<<"Enter the no of rows : "; cin>>rows;
cout<<endl<<"Enter the no of columns : ";cin>>columns; cout<<endl;
int** p = new int* [rows];
for(i = 0; i < rows; i++)
p[i] = new int[columns];
intialise(p,rows,columns);
i = 0, j = 0;
srand (time(NULL));
while(!((i==rows-1)&&(j == columns-1)))
{
//cout<<"hello ";
int temp = rand()%8;
switch(temp)
{
case 1: i--;j++;break;
case 2: j++;break;
case 3: i++;j++;break;
case 4: i++;break;
case 5: i++;j--;break;
default: i = 0; j = 0;count = 1;flag = true; intialise(p,rows,columns); break;
}
if(!flag)
{
if((i>=rows)||(j>=columns)||(i<0)||(j<0)) {i = 0;j=0;count = 1; intialise(p,rows,columns);}
else {count++;p[i][j] = count;}
}
flag = false;
}
cout<<"count: "<<count<<endl;
cout<<"path "<<endl;
for(i = 0;i<rows;i++)
{
for(j = 0; j<columns;j++)
cout<<p[i][j]<<" ";
cout<<endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.