【CodeWars】Path Finder #2: shortest path

题意

题目链接:https://www.codewars.com/kata/path-finder-number-2-shortest-path

Task
You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position [N-1, N-1] if it is possible to reach the exit from the starting position. Otherwise, return false in JavaScript/Python and -1 in C++/C#/Java.

Empty positions are marked .. Walls are marked W. Start and exit positions are guaranteed to be empty in all test cases.

题目意思很清楚,就是求解迷宫的最短路径长度,迷宫格式如下,点表示路,W表示墙,入口是(0,0)位置,出口是最后一行的最后一个点:

".W.\n“”
".W.\n"
 "..."

代码

迷宫有很多求解方法,我采用的是BFS,代码中搜索路径经过的点,其中(x,y)是左边,steps表示到达当前位置经过的步数,当搜索到迷宫出口时放回对应的steps就可以了,需要注意的是BFS使用了队列,需要标记某个位置是否将会被访问,也就是是否已经加入到队列中(这里使用steps作为标记,当steps为0时表示未加入队列,这样可以省去一个变量),需要在座标入队时将对应的steps标记为上一步steps+1,而不是在座标出队的时候标记访问,否则会重复搜索很多的位置,导致时间复杂度爆炸

import java.util.LinkedList;
import java.util.Queue;

public class Finder {

    public static int pathFinder(String maze) {
        maze = maze.replaceAll("\n","");
        StringBuilder stringBuilder = new StringBuilder(maze);
        int n = (int) Math.sqrt(maze.length());
        stringBuilder.replace(0,1,"W");
        Queue<Position> positionQueue = new LinkedList<Position>() {
            {
                offer(new Position(0,0,0));
            }
        };

        int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

        while (!positionQueue.isEmpty()) {
            Position position = positionQueue.poll();
            int i = position.x;
            int j = position.y;
            if (i == n - 1 && j == n - 1) return position.steps;

            for (int k = 0; k < dir.length; k++) {
                int posX = i + dir[k][0];
                int posY = j + dir[k][1];

                if (posX < 0 || posY < 0 || posX >= n || posY >= n || stringBuilder.charAt(posX * n + posY) == 'W')
                    continue;

                positionQueue.offer(new Position(posX,posY,position.steps + 1));
                stringBuilder.replace(posX * n + posY,posX * n + posY + 1,"W");
            }
        }

        return -1;
    }

    static class Position{
        int x;
        int y;
        int steps;

        public Position(int x, int y, int steps) {
            this.x = x;
            this.y = y;
            this.steps = steps;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章