题目链接:P1443 马的遍历
题目描述
有一个 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.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static int[][] map = new int[500][500];
public static int[][] v = new int[500][500];
public static int[][] ans = new int[500][500];
public static int[] dx = new int[]{-2, -1, 1, 2, 2, 1, -1, -2};
public static int[] dy = new int[]{1, 2, 2, 1, -1, -2, -2, -1};
public static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
public static Queue<Node> queue = new LinkedList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
for (int i = 2; i <= n + 1; i++) {
for (int j = 2; j <= m + 1; j++) {
map[i][j] = 1;
}
}
int x = scanner.nextInt();
int y = scanner.nextInt();
Node node = new Node();
node.px = x + 1;
node.py = y + 1;
node.step = 0;
ans[x + 1][y + 1] = 0;
v[x + 1][y + 1] = 1;
queue.add(node);
while (!queue.isEmpty()) {
Node front = queue.peek();
for (int k = 0; k < 8; k++) {
int tx = front.px + dx[k];
int ty = front.py + dy[k];
if (map[tx][ty] == 1 && v[tx][ty] == 0) {
Node tmp = new Node();
tmp.px = tx;
tmp.py = ty;
tmp.step = front.step + 1;
ans[tx][ty] = front.step + 1;
queue.add(tmp);
v[tx][ty] = 1;
}
}
queue.remove();
}
for (int i = 2; i <= n + 1; i++) {
for (int j = 2; j <= m + 1; j++) {
if (ans[i][j] == 0) {
if (i == x + 1 && j == y + 1) {
out.printf(0 + "\t");
} else {
out.printf(-1 + "\t");
}
} else {
out.printf(ans[i][j] + "\t");
}
}
out.println();
}
out.close();
}
}
class Node {
int px;
int py;
int step;
}