zoukankan      html  css  js  c++  java
  • LeetCode第三十六题-判断九宫格是否有效

    Valid Sudoku

    问题简介:确定9x9数独格是否有效, 只需要根据以下规则验证已填充的单元格:

    1.每行必须包含数字1-9而不重复

    2.每列必须包含数字1-9而不重复

    3.网格的9个3x3子框中的每一个必须包含数字1-9而不重复

    注:

    1.数独板(部分填充)可能有效,但不一定是可解决的

    2.只需要根据上述规则验证已填充的单元格

    3.给定的板只包含数字1-9和字符’.’

    4.给定的电路板尺寸始终为9x9

    举例:

    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

    2:

    Input:

    [

    [“8”,“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”]

    ]

    输出: false

    解释: 左上角的3*3里有两个8所以答案为false

    解法一:

    通过set集合对每行每列的元素进行判断,这里的难点是在小的33九宫格里,要注意小九宫格坐标的计算,观察:

    观察行号规律:

    第 i=0 个九宫格:000111222; 第1个九宫格:000111222; 第2个九宫格:000111222;第3个九宫格:333444555; 第4个九宫格:333444555; 第5个九宫格:333444555;第6个九宫格:666777888; 第7个九宫格:666777888; 第8个九宫格:666777888;

    可见对于每三个九宫格行号增3;即可表示为对3作商,因此第i个九宫格的第j个格点的行号加偏移量可表示为i/33+j/3

    观察列号规律:

    第0个九宫格:012012012; 第1个九宫格:345345345; 第2个九宫格:678678678;第3个九宫格:012012012; 第4个九宫格:345345345; 第5个九宫格:678678678;第6个九宫格:012012012; 第7个九宫格:345345345; 第8个九宫格:678678678;

    可见对于下个九宫格列号增3,循环周期为3;对于单个九宫格,每个格点行号增1,周期也为3。因此第i个九宫格的第j个格点的列号加偏移量可表示为i%3*3+j%3

    小白刷题之路,请多指教— — 要么大器晚成,要么石沉大海

  • 相关阅读:
    【血型】+【星座】准到吓人
    一落叶而知秋为什么有些树到冬天要落叶?
    WebDAV介绍
    Ruby concurrency explained
    lexus.cnblogs.com
    微博拉近了大家的距离
    High Performance Ruby Part 3: nonblocking IO and web application scalability
    Taglib确实减轻了开发负担[转]
    php中urldecode()和urlencode()起什么作用啊
    header中ContentDisposition的作用
  • 原文地址:https://www.cnblogs.com/lalalaczq/p/10848622.html
Copyright © 2011-2022 走看看