马的遍历
题目描述
有一个 n × m n \times m n×m 的棋盘,在某个点 ( x , y ) (x, y) (x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
输入格式
输入只有一行四个整数,分别为 n , m , x , y n, m, x, y n,m,x,y。
输出格式
一个 n × m n \times m n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 − 1 -1 −1)。
样例 #1
样例输入 #1
3 3 1 1
样例输出 #1
0 3 2
3 -1 1
2 1 4
提示
数据规模与约定
对于全部的测试点,保证 1 ≤ x ≤ n ≤ 400 1 \leq x \leq n \leq 400 1≤x≤n≤400, 1 ≤ y ≤ m ≤ 400 1 \leq y \leq m \leq 400 1≤y≤m≤400。
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
static class Po{
int x, y;
public Po(int x, int y){
this.x = x;
this.y = y;
}
}
static int N = 410;
static int dist[][] = new int[N][N];
static int n, m, x, y;
static int dx[] = {-1, -2, -2, -1, 1, 2, 2, 1}, dy[] = {-2, -1, 1, 2, 2, 1, -1, -2};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
bfs();
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
System.out.print(dist[i][j] + " ");
}
System.out.println();
}
sc.close();
}
public static void bfs() {
for(int i = 1; i <= n; i++) {
Arrays.fill(dist[i], 1, m+1, -1);
}
dist[x][y] = 0;
LinkedList<Po> q = new LinkedList<>();
q.addLast(new Po(x, y));
while(!q.isEmpty()) {
Po t = q.removeFirst();
for(int i = 0; i < 8; i++) {
int x = t.x + dx[i], y = t.y + dy[i];
if(x > n || x < 0 || y > m || y < 0 || dist[x][y] != -1) continue;
dist[x][y] = dist[t.x][t.y] + 1;
q.addLast(new Po(x, y));
}
}
}
}