Code:
#include <stdio.h>#include<string.h>
#define M 4 // M is a symbol of a maze's rows.
#define N 4 // N is a symbok of a maze's verticals.
// Symbols:
// '1' = open-safe way.
// '0' = closed/blocked.
bool validCell(int maze[M][N], int r_idx, int c_idx);
bool findPath(int maze[M][N], int r_idx, int c_idx, int path[N][N]);
void display_maze(void);
int main(void)
{
char maze[N][M] =
{{ 0,0,1,0 },
{ 1,1,1,0 },
{ 0,1,1,0 },
{ 0,1,1,1 }};
int i,j;
//find the path if available//
if (findPath(maze,0,0,path))
{
printf("success");}
else
printf("failed");
return 0;
}
// check if we can move to a particular cell//
bool validCell(int maze[M][N], int r_idx, int c_idx) {
if (r_idx < 0 || r_idx >= M) {
// invalid M index
return false;
}
if (c_idx < 0 || c_idx >= N) {
// inavlid N index
return false;
}
if (maze[r_idx][c_idx] != 1) {
// cannot move to this cell
return false;
}
return true;
}
/* finds a path from cell (0,0) to cell (M-1,N-1) if a path exists
(r_idx,c_idx) -> M index and N index of the cell
*/
bool findPath(int maze[M][N], int r_idx, int c_idx, int path[N][N]) {
if ((r_idx == M-1) && (c_idx == N-1)) {
// we have reached the last cell
// this implies we have found a path
path[r_idx][c_idx] = 1;
return true;
}
if (validCell(maze,r_idx,c_idx)) {
// cell is valid i.e we can move to the cell
path[r_idx][c_idx] = 0;
// recursively check if a path exists from the current valid (safe) cell
// start checking from cell (r_idx+1,c_idx)
if (findPath(maze,r_idx+1,c_idx,path)) {
return true;
}
// start checking from cell (r_idx,c_idx+1)
if (findPath(maze,r_idx,c_idx+1,path)) {
return true;
}
path[r_idx][c_idx] = 1;
return false;
}
return;
}
I really dont know what's wrong with my code!! and I assure that the recursion part is correct absolutely, I deeply think the error in int main body not in the function itselfs.. If you can tell me what should be re-edited in my code to works finely as appreciated very much.