zoukankan      html  css  js  c++  java
  • LeetCode 1222. 可以攻击国王的皇后

    题目链接

    1222. 可以攻击国王的皇后

    思路分析

    这个题有两种方法了,一种是由皇后去找国王,我们遍历所有的皇后,然后去检查它与国王之间是否有阻挡(同一行、同一列、同一对角线),但是这个办法写出来的代码非常的繁杂,而且还不方便。
    于是第二种方法就出来了,因为国王只有一个,所以我们直接从国王的位置开始向上、下、左、右以及四个对角线方向去寻找皇后,如果找得到就把它纳入结果集。

    代码实现

    class Solution {
        public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
        boolean[][] poss = new boolean[8][8];
        for (int i = 0; i < queens.length; i++) {
            poss[queens[i][0]][queens[i][1]] = true;
        }
        List<List<Integer>> ress = new ArrayList<>();
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}};
        for (int i = 0; i < directions.length; i++) {
            int x = king[0];
            int y = king[1];
            for (; x >= 0 && y >= 0 && x < 8 && y < 8 ; ) {
                if (poss[x][y]) {
                    List<Integer> res = new ArrayList<>();
                    res.add(x);
                    res.add(y);
                    ress.add(res);
                    break;
                } else {
                    x += directions[i][0];
                    y += directions[i][1];
                }
            }
        }
        return ress;
        }
    }
    

    总结

    有时候逆向思维也是非常重要的

  • 相关阅读:
    scapy--初识
    python--re(匹配字符串)
    python--pdb
    Fedora 配置
    Ubuntu 18.04 配置
    python--git
    python--os
    day28 Pyhton 面向对象 继承
    day28 Pyhton MRO和C3算法
    数学知识回顾02
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/13420261.html
Copyright © 2011-2022 走看看