• 【LeetCode】036. 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.

    题解:

    Solution 1 

    class Solution {
    public:
        bool isValidSudoku(vector<vector<char>>& board) {
            const int n = 9;
            
            for(int i = 0; i < n; ++i){
                bool used[n] = {false};
                for(int j = 0; j < n; ++j){
                    if(isused(board[i][j], used))
                        return false;
                }
            }
            for(int i = 0; i < n; ++i){
                bool used[n] = {false};
                for(int j = 0; j < n; ++j){
                    if(isused(board[j][i], used))
                        return false;
                }
            }
            for(int r = 0; r < 3; ++r){
                for(int c = 0; c < 3; ++c){
                    bool used[n] = {false};
                    for(int i = r * 3; i < r * 3 + 3; ++i){
                        for(int j = c * 3; j < c * 3 + 3; ++j){
                            if(isused(board[i][j], used))
                               return false;
                        }
                    }
                }
            }
            return true;
        }
        bool isused(char val, bool used[9]){
            if(val == '.') 
                return false;
            if(used[val - '1'])
                return true;
            used[val - '1'] = true;
            return false;
        }
    };    

    Solution 2 

    class Solution {
    public:
        bool isValidSudoku(vector<vector<char>>& board) {
            const int n = 9;
            vector<vector<bool>> rowboard(n, vector<bool>(n, false));
            vector<vector<bool>> colboard(n, vector<bool>(n, false));
            vector<vector<bool>> celboard(n, vector<bool>(n, false));
            for(int i = 0; i < n; ++i){
                for(int j = 0; j < n; ++j){
                    if(board[i][j] == '.') continue;
                    int ch = board[i][j] - '1';
                    if(rowboard[i][ch] || colboard[ch][j] || celboard[3 * (i / 3) + j / 3][ch])
                        return false;
                    rowboard[i][ch] = true;
                    colboard[ch][j] = true;
                    celboard[3 * (i / 3) + j / 3][ch] = true;
                }
            }
            return true;
        }
    };
  • 相关阅读:
    poj_2417 (baby_step,giant_step算法)
    多校第4场1012
    欧拉回路小结:hihocoder49,50,51
    xor问题的小结(HDU_5269 && HDU_5270 && NEU_1600)
    2015年大连邀请赛F题
    字符串处理——Tire树__LA3942
    15陕西省赛——数学题——n维空间切d刀共能分成多少份???
    ACM荣耀之路;
    选课时间!
    二叉树模板!
  • 原文地址:https://www.cnblogs.com/Atanisi/p/7486846.html
Copyright © 2020-2023  润新知