【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;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章