马的遍历Java

马的遍历

题目描述

有一个 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 1xn400 1 ≤ y ≤ m ≤ 400 1 \leq y \leq m \leq 400 1ym400


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));
				
			}
			
		}	
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值