【Java】BFS最后两个点WA了,求大佬相助!
查看原帖
【Java】BFS最后两个点WA了,求大佬相助!
543167
Enncore楼主2022/4/5 22:09

代码如下:

import java.util.*;

public class Main {
    static int x_1, x_2, y_1, y_2;
    static int[][] map = new int[25][25];
    static boolean[][] visit = new boolean[25][25];
    static int[] dx = {1, 2, 2, 2, 2, 1, -1, -2, -2, -2, -2, -1};
    static int[] dy = {-2, -2, -1, 1, 2, 2, 2, 2, 1, -1, -2, -2};
    static Queue<Node> queue = new ArrayDeque<>();

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        x_1 = input.nextInt();
        y_1 = input.nextInt();
        x_2 = input.nextInt();
        y_2 = input.nextInt();

        initial();
        BFS(x_1, y_1);
        System.out.println(map[1][1]);

        initial();
        BFS(x_2, y_2);
        System.out.println(map[1][1]);

        input.close();
    }

    public static void initial() {
        queue.clear();
        for (int i = 0; i < 25; i++) {
            Arrays.fill(map[i], 0);
            Arrays.fill(visit[i], false);
        }
    }

    public static void BFS(int x, int y) {
        queue.add(new Node(x, y));
        visit[x][y] = true;

        while (queue.size() > 0) {
            Node temp = queue.poll();

            if (temp.x == 1 && temp.y == 1) {
                return;
            }

            for (int i = 0; i < 12; i++) {
                int tx = temp.x + dx[i], ty = temp.y + dy[i];

                if (tx < 0 || tx >= 25 || ty < 0 || ty >= 25) {
                    continue;
                }

                if (!visit[tx][ty]) {
                    visit[tx][ty] = true;
                    queue.add(new Node(tx, ty));
                    map[tx][ty] = map[temp.x][temp.y] + 1;
                }
            }
        }
    }

    static class Node {
        int x, y;

        public Node(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}

2022/4/5 22:09
加载中...