详情链接:1222. 可以攻击国王的皇后
1.问题思路
将国王位置的八个方向进行遍历,当遇到皇后时截断该线路。
2.代码实现
class Solution {
public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
List<List<Integer>> result = new ArrayList<>();
// 8 * 8的棋盘
boolean[][] chessQueue = new boolean[8][8];
// 皇后的位置
for (int i = 0; i < queens.length; i++) {
chessQueue[queens[i][0]][queens[i][1]] = true;
}
int[][] directions = {{-1,-1}, {-1, 0}, {-1, 1}, {0,-1}, {0,1}, {1,-1}, {1,0}, {1,1}};
// 上下左右,和斜着8个反向
for (int i = 0; i < directions.length; i++) {
int x = king[0] + directions[i][0];
int y = king[1] + directions[i][1];
while (x<8 && y<8 && x>=0 && y>=0) {
// 遇到了皇后,进行回溯
if (chessQueue[x][y]) {
result.add(Arrays.asList(x,y));
break;
}
x+=directions[i][0];
y+=directions[i][1];
}
}
return result;
}
}