Finding a cost for a maze path

£可爱£侵袭症+ 提交于 2019-12-13 09:33:38

问题


I have this maze:

    ##++##############
    ##++++++++++++++##
    ########++########
    ##++++++++##----##
    ##++########--####

The "#" symbols are walls in the maze.

The "+" regions of the maze are reachable regions of the maze from the entry point, and the "-" region of the maze are unreachable from the entry point. The entry point is located at the top of the maze.

What I would like to do now is plot a cost of the reachable regions in the maze, which will look like this:

    ##00##############
    ##++02++04++06++##
    ########++########
    ##++08++06##----##
    ##10########--####

This shows that the maze has a cost of 10 from entry to exit.

The maze up top is stored in a 2d array and I used recursion to solve the reachable zones. How can I label costs of the paths using my recursive function, which looks like this:

    void
    flood_fill(m_t * maze, int row, int col) {
        // If row,col is outside maze
        if ( row < 0 || row >= maze->height || col < 0 || col >= maze->width) return;
        // If row,col is not open
        if (maze->M[row][col].type != '.') return;

        // Mark row,col as part of path.
        maze->M[row][col].type = '+';

        // Go LEFT
        flood_fill(maze, row, col - 1);
        // Go DOWN
        flood_fill(maze, row + 1, col);
        // Go RIGHT
        flood_fill(maze, row, col + 1);
        // Go UP
        flood_fill(maze, row - 1, col);

        return;
    }

For the first maze, I used this recursive function at the top of the maze, and it flood filled all the reachable cells with "+".

Are there any suggestions as to how I can do something similar to this but with the path costs instead. I'm just looking for some examples or suggestions as to how I might go about it. Any help on how I can go about achieving the second maze example would be helpful.


回答1:


Pass an extra parameter that is the path cost so far.

flood_fill(m_t * maze, int row, int col, int cost)

Each maze location gets an additional attribute, .cost, which you update as you flood-fill the maze. Initialize the cost to MAXINT as a marker. For instance,

    if (maze->M[row][col].cost > cost)
      maze->M[row][col].cost = cost

    // Go LEFT
    flood_fill(maze, row, col - 1, cost+1);
    // repeat for the other 3 directions

In any case, you now have the cost to each square. Display as desired when you dump the maze to the screen.



来源:https://stackoverflow.com/questions/37303378/finding-a-cost-for-a-maze-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!