- we will start from the king position and check in each of the 8 directions (row 2, col 2, diagonal 2), if there is a queen in the line. Once we’ve found a queen in this direction, we break, cuz it will potentially block the way of other queens in the same line.
- we will use hash-set, to quickly look for queens of one position. we first save all the queens we have into this hash-set and check each time while we loop through all 8 directions.
- note there is a quicker way to cover all positions in all directions
class Solution {
public static String COLON = ":";
public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
List<List<Integer>> result = new ArrayList<>();
Set<String> qset = new HashSet<>();
for(int[] qpos:queens)
qset.add(qpos[0] + COLON + qpos[1]);
int[][] directions = {{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};
for(int[] dir : directions) {
for(int k = 1; k <= 8; k++){
int xpos = king[0] + dir[0] * k;
int ypos = king[1] + dir[1] * k;
if (qset.contains(xpos + COLON + ypos)){
result.add(Arrays.asList(xpos,ypos));
break;
}
}
}
return result;
}
}