In the N-Queen code…int the base condition we made it return false; to print all possible cases…but in this problem rat in a maze code in the base case its returning true then also it prints all the paths…not like the way we did in N-Queen problem…Why is it so?
All possible Cases
@archa_1712 without seeing the code I cannot tell the difference. I you could provide code of N Queen which you are referring to it would be great otherwise I would be just guessing the logic used.
https://ide.codingblocks.com/s/190530 code for N queen
https://ide.codingblocks.com/s/190532 code for Rat maze
Please Reply…
@archa_1712 Hey! both are returning true and one would be printing all possible configurations(rat maze) and other would be printing only one. For printing configuration you would need to return true only (unless you do some modification for indicating that final state is reached.). The difference in the code (in cases when we want to print all cases or only one) is only of the position of return value.
Eg in rat maze, if we modify the code to
> bool rightsuccess=ratinmaze(maze,sol,i,j+1,m,m);
if(rightsuccess) return true; bool downsuccess=ratinmaze(maze,sol,i+1,j,m,n);
it will print only one sol (see here we are returning true as soon as we find a solution, earlier we were checking down irrespective of the value of rightsuccess).
Similarly in n-Queen, instead of directly returning true in for loop , if we use some variable and allow the for loop to execute for all positions we will get all possible results.
bool res=false;
for(int j=0;j<n;j++)
{
//I have to check if i,jth position is safe to place the queen
if(isSafe(board,i,j,n))
{
//Place the queen - Assuming i,j is the right position
board[i][j] = 1;
res = SolveNQueen(board,i+1,n)||res;//Means i,j is not the right position - Assumption is wrong board[i][j] = 0; //backtrack } }
Now it will print all configurations.
I hope this helps.
if this solves your doubt please mark it as resolved.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.