题解 | 走迷宫

走迷宫

https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64

import java.util.Scanner;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String s = in.nextLine();
        String[] split = s.split(" ");

        String position = in.nextLine();
        String[] positionS = position.split(" ");

        Integer first = new Integer(split[0]);
        Integer second = new Integer(split[1]);
        String[][] write = new String[first][second];
        for (int i = 0; i < first; i++) {
            String data = in.nextLine();
            String[] s1 = data.split("");
            write[i] = s1;
        }
        System.out.println(getResult(positionS, write, first - 1, second - 1));
    }

    public static int getResult( String[] positionS, String[][] write,
                                 Integer first, Integer second) {
        Queue<int[]> data = new LinkedList<>();
        data.add(new int[] {new Integer(positionS[0]) - 1, new Integer(positionS[1]) - 1, 0});
        Integer endX = new Integer(positionS[2]) - 1;
        Integer endY = new Integer(positionS[3]) - 1;

        while (!data.isEmpty()) {
            int[] poll = data.poll();
            if (poll[0] == endX && poll[1] == endY) {
                return poll[2];
            }
            if (poll[0] + 1 <= first  &&
                    write[poll[0] + 1][poll[1]].equals(".")) {
                data.offer(new int[] {poll[0] + 1, poll[1],  poll[2] + 1});
                write[poll[0] + 1][poll[1]] = "/";
            }
            if (poll[0] - 1 >= 0  &&
                    write[poll[0] - 1][poll[1]].equals(".")) {
                data.offer(new int[] {poll[0] - 1, poll[1],  poll[2] + 1});
                write[poll[0] - 1][poll[1]] = "/";
            }
            if (poll[1] + 1 <= second  &&
                    write[poll[0]][poll[1] + 1].equals(".")) {
                data.offer(new int[] {poll[0], poll[1] + 1,  poll[2] + 1});
                write[poll[0]][poll[1] + 1] = "/";
            }
            if (poll[1] - 1 >= 0  &&
                    write[poll[0]][poll[1] - 1].equals(".")) {
                data.offer(new int[] {poll[0], poll[1] - 1,  poll[2] + 1});
                write[poll[0]][poll[1] - 1] = "/";
            }
        }
        return -1;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务