来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/queens-that-can-attack-the-king/
一,问题描述
TIPS:
1.1 解释
题目已经交代的比较清楚了,就是将第一个在八个方向上“碰到”king的坐标记录下来。没有技巧,纯纯的都是磨炼你的coding能力。碰到这种类型的题目一般都是从小的部分来进行考虑求解问题的思路和步骤可能会简洁一些。
- 一般定义八个方向,在一个方向上进行延展,一直碰到有queue或者是峭壁即可。
二,题解
// 对于四个方向的问题都要习惯去定义数组来进行求解
int[][] dist = new int[][]{{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};
public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
List<List<Integer>> res = new ArrayList<>();
int[][] grid = new int[8][8];
for (int i = 0; i < queens.length; i++) {
grid[queens[i][0]][queens[i][1]] = 1;
}
// 8个方向
for (int k = 0; k < 8; k++) {
int x = king[0] + dist[k][0];
int y = king[1] +dist[k][1];
while( x >= 0 && x <= 8 && y >= 0 && y <= 8){
if(grid[x][y] == 1){
res.add(new ArrayList<>(Arrays.asList(x,y)));
break;
}
x += dist[k][0];
y += dist[k][1];
}
}
return res;
}
三,复杂度分析
时间:时间复杂度O(N*N)
空间:空间复杂度O(N)
总结
在看到这种题目的时候,如何写出简洁清晰易读的代码,也是一种挑战。