题目地址:
https://leetcode.com/problems/queens-that-can-attack-the-king/
给定一个棋盘的若干座标,横纵座标范围为,这些座标上有国际象棋里的皇后,再给定一个座标代表国王的位置(国王不会和皇后重合),问能攻击到国王的皇后座标。注意能攻击到国王的皇后,攻击路径上不能有其他棋子。
可以先将所有皇后的座标加入一个哈希表,然后从国王的位置向八个方向走,每遍历一个方向的时候,遇到的第一个皇后就加入最终结果并退出循环,继续搜索下一个方向。代码如下:
import java.util.*;
public class Solution {
class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
Pair pair = (Pair) o;
return x == pair.x && y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
List<List<Integer>> res = new ArrayList<>();
if (queens == null || queens.length == 0) {
return res;
}
// 加入所有皇后座标
Set<Pair> set = new HashSet<>();
for (int[] coord : queens) {
set.add(new Pair(coord[0], coord[1]));
}
// 开个数组表示八个方向
int[][] d = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}};
for (int i = 0; i < d.length; i++) {
int x = king[0], y = king[1], curX = x, curY = y;
while (0 <= curX && curX < 8 && 0 <= curY && curY < 8) {
curX += d[i][0];
curY += d[i][1];
if (set.contains(new Pair(curX, curY))) {
res.add(new ArrayList<>(Arrays.asList(curX, curY)));
break;
}
}
}
return res;
}
}
时空复杂度。