/* A recursive utility function to solve Maze problem */ bool solveMazeUtil(int maze[m][n], int x, int y, int sol[m][n]) { // if (x,y is goal) return true if(x == m-1 && y == n-1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if(isSafe(maze, x, y) == true) { // mark x,y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x+1, y, sol) == true) return true; /* If x moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y+1, sol) == true) return true; /* If none of the above movements work then BACKTRACK: unmark x,y as part of solution path */ sol[x][y] = 0; return false; } return false; }
bool solveMazeUtil(int **maze, int x, int y, int x2, int y2, int **sol) { // if (x,y is goal) return true if (x == x2 && y == y2) { sol[x][y] = 1; p[count_p][0] = x; p[count_p][1] = y; count_p += 1; return true; } if (isSafe(maze, x, y, x2, y2) == true) { sol[x][y] = 1; if (solveMazeUtil(maze, x + 1, y, x2, y2, sol) == true){ p[count_p][0] = x; p[count_p][1] = y; count_p += 1; return true; } if (solveMazeUtil(maze, x, y + 1, x2, y2, sol) == true){ p[count_p][0] = x; p[count_p][1] = y; count_p += 1; return true; } if (solveMazeUtil(maze, x - 1, y, x2, y2, sol) == true){ p[count_p][0] = x; p[count_p][1] = y; count1 += 1; return true; } if (solveMazeUtil(maze, x, y - 1, x2, y2, sol) == true){ p[count_p][0] = x; p[count_p][1] = y; count_p += 1; return true; } sol[x][y] = 0; return false; } return false; }
bool solveMaze(int maze[m][n]) { if(solveMazeUtil(maze, 0, 0, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol); return true; }
/* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveMaze(int maze[N][N]) { int sol[N][N] = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} }; if(solveMazeUtil(maze, 0, 0, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol); return true; }
bool solveMaze(int **maze, int m, int n) { int **sol = (int**)calloc(m, sizeof(int)*m); for (int j = 0; j < n; j++){ sol[j] = (int*)calloc(n, sizeof(int)); } int x1 = 1, y1 = 1, x2 = 2, y2 = 2; if (solveMazeUtil(maze, x1, y1, x2, y2, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol, m, n); return true; }