milardovich

Maze solver using backtracking

Mar 24th, 2014
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. /*
  2.  * Simple maze solver
  3.  * Author: Sergio Milardovich <[email protected]>
  4.  * Based on http://www.youtube.com/watch?v=FJkT_dRjX94&list=PLTZbNwgO5ebpqWBmBx0lpy9IYFMSQcrL-
  5.  * This script is only for academic usage
  6.  */
  7.  
  8. #include <math.h>
  9. #include <stdbool.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <time.h>
  13.  
  14. bool isValid(int M[999][999], int i, int j);
  15. bool solveMazeUtil(int M[999][999], int x, int y, int sol[999][999]);
  16.  
  17.  
  18. void generateRandomMaze(int M[999][999], int sol[999][999]);
  19. void printMaze(int maze[999][999]);
  20. void solveMaze(int M[999][999], int sol[999][999]);
  21.  
  22. int m,n;
  23. int M[999][999];
  24. int sol[999][999];
  25.  
  26. void main(){
  27.     srand(time(NULL));
  28.  
  29.     scanf("%d", &m);
  30.     scanf("%d", &n);
  31.  
  32.     generateRandomMaze(M,sol);
  33.     printMaze(M);
  34.  
  35.     printf("\n");
  36.     solveMaze(M,sol);
  37.     printf("\n");
  38. }
  39.  
  40. bool isValid(int M[999][999], int i, int j){
  41.     if((i >= 0 && i <= m) && (j >= 0 && j <= n) && M[i][j] == 1){
  42.         return true;
  43.     } else {
  44.         return false;
  45.     }
  46. }
  47.  
  48. void solveMaze(int M[999][999], int sol[999][999]){
  49.     if(solveMazeUtil(M,0,0,sol) == false){
  50.         printf("No solution");
  51.     } else {
  52.         printMaze(sol);
  53.     }
  54. }
  55.  
  56. bool solveMazeUtil(int M[999][999], int x, int y, int sol[999][999]){
  57.     if(x == m-1 && y == n-1){
  58.         sol[x][y] = 1;
  59.         return true;
  60.     }
  61.     if(isValid(M,x,y) == true){
  62.         sol[x][y] = 1;
  63.  
  64.         if (solveMazeUtil(M, x+1, y, sol) == 1)
  65.             return true;
  66.  
  67.         if (solveMazeUtil(M, x, y+1, sol) == 1)
  68.             return true;
  69.  
  70.         sol[x][y] = 0;
  71.         return false;
  72.     }
  73.     return false;
  74. }
  75.  
  76. void generateRandomMaze(int M[999][999], int sol[999][999]){
  77.     int i,j;
  78.     for(i=0;i<m;i++){
  79.         for(j=0;j<n;j++){
  80.             M[i][j] = (rand()%2);
  81.             sol[i][j] = 0;
  82.         }
  83.     }
  84. }
  85.  
  86. void printMaze(int maze[999][999]){
  87.     int i,j;
  88.     for(i=0;i<m;i++){
  89.         for(j=0;j<n;j++){
  90.             printf("%d ",maze[i][j]);
  91.         }
  92.         printf("\n");
  93.     }
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment