Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Simple maze solver
- * Author: Sergio Milardovich <[email protected]>
- * Based on http://www.youtube.com/watch?v=FJkT_dRjX94&list=PLTZbNwgO5ebpqWBmBx0lpy9IYFMSQcrL-
- * This script is only for academic usage
- */
- #include <math.h>
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- bool isValid(int M[999][999], int i, int j);
- bool solveMazeUtil(int M[999][999], int x, int y, int sol[999][999]);
- void generateRandomMaze(int M[999][999], int sol[999][999]);
- void printMaze(int maze[999][999]);
- void solveMaze(int M[999][999], int sol[999][999]);
- int m,n;
- int M[999][999];
- int sol[999][999];
- void main(){
- srand(time(NULL));
- scanf("%d", &m);
- scanf("%d", &n);
- generateRandomMaze(M,sol);
- printMaze(M);
- printf("\n");
- solveMaze(M,sol);
- printf("\n");
- }
- bool isValid(int M[999][999], int i, int j){
- if((i >= 0 && i <= m) && (j >= 0 && j <= n) && M[i][j] == 1){
- return true;
- } else {
- return false;
- }
- }
- void solveMaze(int M[999][999], int sol[999][999]){
- if(solveMazeUtil(M,0,0,sol) == false){
- printf("No solution");
- } else {
- printMaze(sol);
- }
- }
- bool solveMazeUtil(int M[999][999], int x, int y, int sol[999][999]){
- if(x == m-1 && y == n-1){
- sol[x][y] = 1;
- return true;
- }
- if(isValid(M,x,y) == true){
- sol[x][y] = 1;
- if (solveMazeUtil(M, x+1, y, sol) == 1)
- return true;
- if (solveMazeUtil(M, x, y+1, sol) == 1)
- return true;
- sol[x][y] = 0;
- return false;
- }
- return false;
- }
- void generateRandomMaze(int M[999][999], int sol[999][999]){
- int i,j;
- for(i=0;i<m;i++){
- for(j=0;j<n;j++){
- M[i][j] = (rand()%2);
- sol[i][j] = 0;
- }
- }
- }
- void printMaze(int maze[999][999]){
- int i,j;
- for(i=0;i<m;i++){
- for(j=0;j<n;j++){
- printf("%d ",maze[i][j]);
- }
- printf("\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment