• leetcode 有效的数独


    判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

    1. 数字 1-9 在每一行只能出现一次。
    2. 数字 1-9 在每一列只能出现一次。
    3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

    上图是一个部分填充的有效的数独。
    数独部分空格内已填入了数字,空白格用 '.' 表示。

    示例 1:

    输入:
    [
    ["5","3",".",".","7",".",".",".","."],
    ["6",".",".","1","9","5",".",".","."],
    [".","9","8",".",".",".",".","6","."],
    ["8",".",".",".","6",".",".",".","3"],
    ["4",".",".","8",".","3",".",".","1"],
    ["7",".",".",".","2",".",".",".","6"],
    [".","6",".",".",".",".","2","8","."],
    [".",".",".","4","1","9",".",".","5"],
    [".",".",".",".","8",".",".","7","9"]
    ]
    输出: true

    看见这道题我觉得应该能做出来,因为我做过五子棋,也是自己研究的数组棋盘遍历,感觉差不多
    然而,没想到,做出来就用了我小半个下午的时间,并且用的也是很笨的遍历办法…

    var isValidSudoku = function (board) {
        //横向遍历
        for (let i = 0; i !== 9; i++) {
            let temp = board[i].filter(value => value !== ".");
            if (new Set(temp).size !== temp.length) {
                return false;
            }
        }
        //纵向遍历
        for (let i = 0; i !== 9; i++) {
            let temp = board.map(value => value.filter((value, index) => index === i)).map(value => value[0]).filter(value => value !== ".");
            if (new Set(temp).size !== temp.length) {
                return false;
            }
        }
        //3x3宫格遍历
        for (let i = 0; i < 9; i += 3) {
            //先分为3个9x3的
            let temp = board.map(value => value.filter((value, index) => index >= i && index < i + 3)).filter(value => value !== ".");
            //再把9x3分成3个3x3
            for (let j = 0; j < 9; j += 3) {
                //转为1维数组去重判断长度
                let temp_3x3 = temp.filter((value, index) => index >= j && index < j + 3).join(",").split(",").filter(value => value !== ".");
                if (new Set(temp_3x3).size !== temp_3x3.length) {
                    return false;
                }
            }
        }
        return true;
    };
    

    方法是很笨的硬莽干

  • 相关阅读:
    Windows 命令行
    建议博客园提供 BT 资源发布功能——由分享 VS2005 Beta2 的历程想到的
    成功 自信 快乐(转载)
    轻松一下,加菲猫语录
    COmega 概述
    对 RBAC 几种模型的理解及初步实现构想
    DHTML 中滚动条的设置
    求婚
    终于有了自己的blog!
    VS2005 已发布!
  • 原文地址:https://www.cnblogs.com/sbzy/p/9382690.html
Copyright © 2020-2023  润新知