find path/route in a maze 2 d matrix

http://www.geeksforgeeks.org/backttracking-set-2-rat-in-a-maze/

#include<stdio.h>
#include <stdbool.h>

// Maze size
#define N 4 

void printSolution(int sol[N][N])
{
    int i, j;
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < N; j++)
            printf(" %d ", sol[i][j]);
        printf("\n");
    }
}

/* A recursive utility function to solve Maze problem */
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N])
{
    // if (x,y is goal) return true
    if(x == N-1 && y == N-1)
    {
        sol[x][y] = 1;
        return true;
    }

    if(x < 0 || x >= N || y < 0 || y >= N )
        return false;

    if(maze[x][y] != 1) 
        return false;

    // 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 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;
}

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;
}



// driver program to test above function
int main()
{
    int maze[N][N] = { {1, 0, 0, 0},
        {1, 1, 0, 1},
        {0, 1, 0, 0},
        {1, 1, 1, 1}
    };

    solveMaze(maze);
    getchar();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章