【洛谷】P1443 - 马的遍历

public class Main {
    static int N ;
    static int M ;
    static int MX ;
    static int MY;
    static int[][] area ;
    static int[][] map ;
    static int count ;

    static int[] px = {-2,-2,-1,1,2,2,1,-1};
    static int[] py = {-1,1,2,2,1,-1,-2,-2};
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        N = sc.nextInt();
        M = sc.nextInt();
        MX = sc.nextInt();
        MY = sc.nextInt();
        
        area = new int[N+1][M+1];
        map = new int[N+1][M+1];
        count = 0;
        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= M; j++) {
                area[i][j] = Integer.MAX_VALUE;
                map[i][j] = Integer.MAX_VALUE;
            }
        }
        
        area[MX][MY] = 1 ;
        map[MX][MY] = 0;
        bfs(MX,MY);
        
        
        //呈矩阵输出
        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= M; j++) {
                if (map[i][j] == Integer.MAX_VALUE) {
                    map[i][j] = -1;
                }
                System.out.printf("%-5d",map[i][j]);
            }
            System.out.println();
        }
        
        
        
    }
    
    private static void bfs(int x, int y) {
        LinkedList Q = new LinkedList();
        Point pt = new Point(x,y,0); //
        Q.add(pt);
        
        while(!Q.isEmpty()) {
            Point cur = Q.poll();
            int curx = cur.hz;
            int cury = cur.zz;
            int curn = cur.num;
            
            for (int i = 0; i < 8; i++) {
                int newx = px[i] + curx ;
                int newy = py[i] + cury ;
                count = curn + 1;
                
                if (newx >= 1 && newx <= N && newy >= 1 && newy <= M && area[newx][newy] != 1) {
                    area[newx][newy] = 1;
                    map[newx][newy] = count;
                    Q.add(new Point(newx,newy,count));
                }
            }
        }
        
    }
    
    private static class Point{
        int hz;
        int zz;
        int num;

        public Point(int hz, int zz, int num) {
            this.hz = hz;
            this.zz = zz;
            this.num = num;
        }
    }

}

你可能感兴趣的:(【洛谷】P1443 - 马的遍历)