leetcode 1222. Queens That Can Attack the King

请添加图片描述
请添加图片描述

  • 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;
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值