题目出处
思路:很明显用广搜,一层一层的搜,每一次用队列把走到相应坐标和步数记录下来,最后只要搜到就把步数输出即可。
代码如下:
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;
}
}
}
}
}
}