zoukankan      html  css  js  c++  java
  • Leetcode Valid Sudoku

    class Solution {
    private:
        // only used by _isValidSudoku
        int row[9];
        int col[9];
        int blk[9];
    public:
        bool _isValidSudoku(vector<vector<char> >& board) {
            if (board.empty()) return true;
            memset(row, 0, sizeof(row));
            memset(col, 0, sizeof(col));
            memset(blk, 0, sizeof(blk));
            int rm, cm, bm;
            for (int i=0; i<9; i++) {
                int base = i / 3 * 3;
                for (int j=0; j<9; j++) {
                    char ch = board[i][j];
                    if (ch == '.') continue;
                    int msk = 0x1<<(ch - '0');
                    int blk_idx = base + j / 3;
                    rm = msk|row[i];
                    cm = msk|col[j];
                    bm = msk|blk[blk_idx];
                    if (rm == row[i] || cm == col[j] || bm == blk[blk_idx]) {
                        return false;
                    }
                    row[i] = rm;
                    col[j] = cm;
                    blk[blk_idx] = bm;
                }
            }
            return true;
        }
        
        bool isValidSudoku(vector<vector<char> >& board) {
            if (board.empty()) return true;
            int mx = board.size() - 1;
            int my = board[0].size() - 1;
            // each row
            for (int i=0; i <= my; i++) {
                if (!isValidRegion(board, 0, i, mx, 0)) return false;
            }
            // each column
            for (int i=0; i <= mx; i++) {
                if (!isValidRegion(board, i, 0, 0, my)) return false;
            }
            // each block
            for (int i=0; i<3; i++) {
                for (int j=0; j<3; j++){
                    if (!isValidRegion(board, j*3, i*3, 2, 2)) return false;   
                }
            }
            return true;
        }
        bool isValidRegion(vector<vector<char> >& board, int sx, int sy, int dx, int dy) {
            char count[10];
            for (int i=0; i<10; i++) count[i] = 0;
            
            for (int i=sy + dy; i >= sy; i--) {
                for (int j=sx + dx; j >= sx; j--) {
                    char num = board[i][j];
                    if (num == '.') continue;
                    if (num > '9' || num < '0') return false;
                    if (++count[num-'0'] > 1) return false;
                }    
            }
            return true;
        }
    };

    isValidSudoku 使用常用方法判断
    _isValidSudoku 使用位运算进行判断,不过这里也没什么提升

  • 相关阅读:
    第五章 Python——字符编码与文件处理
    第六章 Python——函数与面向过程编程
    第七章 Python——模块与包
    第一章 计算机硬件基础与操作系统介绍
    luogu P1706 全排列问题
    luogu 2142 高精度减法
    luogu P1601 高精度加法
    luogu P1803 线段覆盖 贪心
    luogu P1031 均分纸牌 贪心
    luogu P2678 跳石头 二分答案
  • 原文地址:https://www.cnblogs.com/lailailai/p/3597375.html
Copyright © 2011-2022 走看看