Rat in a maze problem using backtracking - #278
Open
jasmine-k05 wants to merge 1 commit into
Open
Conversation
Rat in a maze problem using backtracking
Owner
|
Please add the entire questions on top as a comment. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
/* C++ program for rat in a maze problem */
#include
using namespace std;
bool isSafe(int r,int c,int n,int **maze)
{
if( r < 0 || r >= n )
return false;
if( c < 0 || c >= n )
return false;
if(maze[r][c])
return true;
return false;
}
bool solvemaze(int ** maze,int i,int j,int ** soln,int n)
{
if(i == n-1 && j == n-1)
{
soln[i][j]=1;
return true;
}
if(isSafe(i,j,n,maze))
{
soln[i][j]=1;
if(solvemaze(maze,i+1,j,soln,n))
return true;
if(solvemaze(maze,i,j+1,soln,n))
return true;
soln[i][j]=0;
}
return false;
}
int main()
{
int n;
cin>>n;
int** maze = new int*[n];
for(int i = 0; i < n; ++i)
maze[i] = new int[n];
int** soln = new int*[n];
for(int i = 0; i < n; ++i)
soln[i] = new int[n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>maze[i][j];
soln[i][j]=0;
}
}
if(solvemaze(maze,0,0,soln,n))
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<soln[i][j]<<" ";
cout<<endl;
}
}
else
{
cout<<"-1";
}
}