Sunday, May 5, 2013

Maze Problem with Two directional(right and down) Movement for all the possible Path from Source to destination

Algo:-

1) Start with position(x=0,y=0) 
2) Check, it is valid or not. if Valid then, mark it with 1.
3) Move towards Right, then follow step 2.
4) Move towards Down, then follow step 2.
5) Print all the mark position

Code:-


#define N 4

bool mazeProblemUtil(int maze[N][N], int x, int y, int sol[N][N]);

/* A utility function to print solution  */
void printMazeSolution(int sol[N][N])
{
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
            printf(" %d -", sol[i][j]);
        printf("\n");
    }
}

/* Check if x,y is valid index for N*N maze */
bool isSafeMark(int maze[N][N], int x, int y)
{
    // if (x,y outside maze) return false
    if(x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1)
        return true;

    return false;
}


/* Utility function to solve Maze problem */
bool mazeProblemUtil(int maze[N][N], int x, int y, int sol[N][N])
{
    /* Reached Target*/
    if(x == N-1 && y == N-1)
    {
        sol[x][y] = 1;
        return true;
    }
    int cnt = 0;

    if(isSafeMark(maze, x, y) == true)
    {
        // mark as part of solution path
        sol[x][y] = 1;

        /* moving Right  */
        if ((mazeProblemUtil(maze, x, y+1, sol) == true) )
        {
            printf("\n");                    
            printMazeSolution(sol);
        }
       

        /* moving Down */
        if (mazeProblemUtil(maze, x+1, y, sol) == true)
        {
            printf("\n");
            printMazeSolution(sol);
        }

        /* Backtrack if not matching */
        sol[x][y] = 0;
        return false;
    }  
    return false;
}


void mazeProblem(int maze[N][N])
{
   /* O/p matrix will change with different input matrix dimension*/
    int sol[N][N] = { {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[N][N]  =  {
        {1, 1, 0, 0},
        {1, 1, 1, 1},
        {1, 0, 0, 1},
        {1, 1, 1, 1}
    };


No comments:

Post a Comment