洛谷P1747 Java解法

题目出处
在这里插入图片描述
思路:很明显用广搜,一层一层的搜,每一次用队列把走到相应坐标和步数记录下来,最后只要搜到就把步数输出即可。

代码如下:

package search;

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

public class P1747 {

	static int x1, y1, x2, y2;
	static int[] xx = { 1, 1, -1, -1, 2, 2, -2, -2, 2, 2, -2, -2 };
	static int[] yy = { 2, -2, 2, -2, 1, -1, 1, -1, -2, 2, -2, 2 };

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		x1 = sc.nextInt();
		y1 = sc.nextInt();
		x2 = sc.nextInt();
		y2 = sc.nextInt();
		bfs(x1, y1);
		bfs(x2, y2);
	}

	public static void bfs(int X, int Y) {
		boolean[][] vis = new boolean[21][21];
		Queue<Integer> row = new LinkedList<Integer>();// 存储横坐标
		Queue<Integer> col = new LinkedList<Integer>();// 存储纵坐标
		Queue<Integer> step = new LinkedList<Integer>();// 存储走到这里用了几步
		row.add(X);
		col.add(Y);
		step.add(0);
		vis[X][Y] = true;
		while (!row.isEmpty()) {
			int x = row.poll();
			int y = col.poll();
			int s = step.poll();
			for (int i = 0; i < 12; i++) {
				if (x + xx[i] >= 1 && x + xx[i] <= 20 && y + yy[i] >= 1 && y + yy[i] <= 20
						&& !vis[x + xx[i]][y + yy[i]]) {
					row.add(x + xx[i]);
					col.add(y + yy[i]);
					step.add(s+1);
					vis[x][y] = true;
					if (x + xx[i] == 1 && y + yy[i] == 1) {//因为是广搜,只要找到了肯定就是最短路
						System.out.println(s+1);
						return;
					}
				}
			}

		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值