bidirection bfs
https://blog.csdn.net/hzt12345hf/article/details/79137318 knight巡逻
给一个infinite board,起点终点,国际象棋的king,问怎么得到最短距离。bfs,在追问下想到O(1)。然后棋子改成knight,问最短距离。我说了bfs,然后说可以双向bfs优化,他问can you do better than that?想不出,最后让我写了个简单的bfs。想问这个knight可以减枝吗?对国际象棋真的不是很了解。
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
class Solution {
public static void main(String[] args) throws InterruptedException {
Solution s = new Solution();
int[][] array = new int[][] {{0,1},{1,3}};
System.out.println(s.count(array) - 2);
}
static class Point {
int x,y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
int[][][] board;
public int count(int[][] points) {
board = new int[50][50][2];
Queue<Point> q1 = new LinkedList<>();
Queue<Point> q2 = new LinkedList<>();
Point p1 = new Point(points[0][0],points[0][1]);
q1.offer(p1);
board[points[0][0]][points[0][1]][0] = 1;
Point p2 = new Point(points[1][0],points[1][1]);
board[points[1][0]][points[1][1]][1] = 1;
q2.offer(p2);
int[] prevCount = new int[] {1,1};
while (!q1.isEmpty() && !q2.isEmpty()) {
if (q1.size() < q2.size()) {
int a1 = work(q1,prevCount,0);
if (a1 != -1) return a1;
} else {
int a2 = work(q2,prevCount,1);
if (a2 != -1) return a2;
}
}
return -1;
}
int[][] dir = new int[][] {{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
public int work(Queue<Point> q, int[] prevCount, int index){
int count = 0;
for (int i = 0; i < prevCount[index]; i++) {
Point cur = q.poll();
for (int j = 0; j < 8; j++) {
int x = cur.x + dir[j][0];
int y = cur.y + dir[j][1];
if (x < 0 || x >= 30 || y < 0 || y >= 30) continue;
if (board[x][y][0] != 0 && board[x][y][1] != 0) {
return board[x][y][1] + board[x][y][0];
}
if (board[x][y][index] != 0) continue;
count++;
board[x][y][index] = board[cur.x][cur.y][index] + 1;
Point p = new Point(x,y);
q.offer(p);
}
}
prevCount[index] = count;
return -1;
}
}