Sunday, May 5, 2013

Maze Problem With Four Directional Movement(Left, Right, Up, Down)

Algo:-
1) Start with Position (x= 0, y=0)
2) If Reached the target,then Print the path.
3) Otherwise Check Below Condition
   3.1) Is it in boundary
   3.2) Is it valid(i.e maze[x][y] == 1)
   3.3) If Valid, then check Is it visited(i.e maze[x][y] == 2)
   4) Move Up(x-1,y)
   5) Move Right(x,y+1)
   6) Move Down(x+1,y)
   7) Move Left(x,y-1)

Code:-


 // if (x,y outside maze && path is not valid && visited) return false
bool isMazeSafe(int maze[M][N], int x, int y)
{

    if(x >= 0 && x < M && y >= 0 && y < N && maze[x][y] == 1 && maze[x][y] != 2)
    {
        /*Mark as visited, also can be done other way*/
         maze[x][y] = 2;
         return true;
    }

    return false;
}


/* A recursive function to solve mazeProblem */
int mazeProblemUtil(int maze[M][N], int x, int y, int sol[M][N])
{
    // Reached Target
    if(x == M-1 && y == N-1)
    {
        sol[x][y] = 1;
        return true;
    }

    if(isMazeSafe(maze, x, y) == true)
    {
        // mark as it is valid
        sol[x][y] = 1;
     
        /* Move Up */
        if(x > 0)
        {
         if (mazeProblemUtil(maze, x-1, y, sol) == true)
         {
            printf("\n");
            printMazeSolution(sol);
         }
        }
        /* Move right */
        if ((mazeProblemUtil(maze, x, y+1, sol) == true) )
        {
            printf("\n");                  
            printMazeSolution(sol);
        }
        /* Move down */
        if (mazeProblemUtil(maze, x+1, y, sol) == true)
        {
            printf("\n");
            printMazeSolution(sol);
        }
        /* Move left */
        if(y > 0)
        {
         if (mazeProblemUtil(maze, x, y-1, sol) == true)
         {
            printf("\n");
            printMazeSolution(sol);
         }
        }

        /* Backtrack if no path*/
        sol[x][y] = 0;
        return false;
    }

    return false;
}
void mazeProblem(int maze[M][N])
{
   /*Output Matrix can be differ with dimension with i/p Matrix Dimension*/
    int sol[M][N] = {
        {0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0}
    };

    mazeProblemUtil(maze, 0, 0, sol);
 
}


i/p:-


    int maze[M][N]  =  {
        {1, 1, 0, 0, 0},
        {0, 1, 0, 0, 0},
        {1, 1, 0, 0, 0},
        {1, 0, 1, 1, 1},
        {1, 1, 1, 0, 1}
    };




No comments:

Post a Comment