zoukankan      html  css  js  c++  java
  • 【LeetCode】36. Valid Sudoku

    题目:

    Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

    The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

    A partially filled sudoku which is valid.

    Note:
    A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

    提示:

    此题最主要的难点其实是如何记录每一块中数字出现的情况(每行和每列比较简单)。

    如果我们以从左到右,从上到下的顺序给每一块标定次序的话,那个对于第i行j列的元素,它隶属于i / 3 * 3 + j / 3。

    这个问题解决之后,其他问题也就比较简单了。

    代码:

    class Solution {
    public:
        bool isValidSudoku(vector<vector<char>>& board) {
            int mark_row[9][9] = {0}, mark_col[9][9] = {0}, mark_block[9][9] = {0};
            for (int i = 0; i < 9; ++i) {
                for (int j = 0; j < 9; ++j) {
                    if (board[i][j] == '.') continue;
                    int idx = board[i][j] - '1', k = i / 3 * 3 + j / 3;
                    if (mark_row[i][idx] || mark_col[j][idx] || mark_block[k][idx]) return false;
                    else mark_row[i][idx] = mark_col[j][idx] = mark_block[k][idx] = 1;
                }
            }
            return true;
        }
    };
  • 相关阅读:
    面向接口程序设计思想实践
    Block Chain Learning Notes
    ECMAScript 6.0
    Etcd Learning Notes
    Travis CI Build Continuous Integration
    Markdown Learning Notes
    SPRING MICROSERVICES IN ACTION
    Java Interview Questions Summary
    Node.js Learning Notes
    Apache Thrift Learning Notes
  • 原文地址:https://www.cnblogs.com/jdneo/p/4748271.html
Copyright © 2011-2022 走看看