java#5和#9超时求助
查看原帖
java#5和#9超时求助
295827
红菜头糕楼主2020/11/23 19:20

代码如下

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    static int pointX, pointY;    
    static int[][] move = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};    
    static int upper, lower, left, right;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x, y;
        x = sc.nextInt();
        y = sc.nextInt();
        pointX = sc.nextInt() - 1;
        pointY = sc.nextInt() - 1;
        upper = left = -1;
        lower = x;
        right = y;
        int[][] arr = new int[x][y];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                if (i == pointX && j == pointY) {
                    continue;
                }
                bfs(arr, i, j, new boolean[x][y]);
            }
        }
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                System.out.printf("%-5d",arr[i][j]);
            }
            System.out.println();
        }
    }

    static void bfs(int[][] arr, int targetX, int targetY, boolean[][] vis) {
        int count = 0;
        LinkedList<Point> linkedList = new LinkedList<>();
        vis[pointX][pointY] = true;
        linkedList.offer(new Point(pointX, pointY, 0));
        while (!linkedList.isEmpty()) {
            Point current = linkedList.poll();
            current.count++;
            for (int i = 0; i < 8; i++) {
                int x = current.x + move[i][0];
                int y = current.y + move[i][1];
                if (x == targetX && y == targetY) {    
                    arr[targetX][targetY] = current.count;
                    return;
                }
                if (x > upper && x < lower && y > left && y < right) {    
                    if (!vis[x][y]) {   
                        vis[x][y] = true;
                        linkedList.offer(new Point(x, y, current.count));
                    }
                }
            }
        }
        arr[targetX][targetY] = -1;
    }
}

class Point {
    int x;
    int y;
    int count;

    Point(int x, int y, int count) {
        this.x = x;
        this.y = y;
        this.count = count;
    }
}
已尝试O2,还是不行,求助dalao有优化思路嘛
2020/11/23 19:20
加载中...