Not too concise but straightforward code, using an array of size 9


  • 0
    Q
    class Solution {
    public:
        bool isValidSudoku(vector<vector<char>>& board) {
            for(int i=0;i<9;++i) {
                int buf[9]={0}, *p=&buf[-1-'0'];
                for(auto v: board[i]) if(v!='.') ++p[v];
                for(p=&buf[0];p!=&buf[9];++p) if(*p>1) return false;
            }
            for(int i=0;i<9;++i) {
                int buf[9]={0}, *p=&buf[-1-'0'];
                for(auto &v: board) if(v[i]!='.') ++p[v[i]];
                for(p=&buf[0];p!=&buf[9];++p) if(*p>1) return false;
            }
            for(int i=0;i<9;i+=3) {
                for(int j=0;j<9;j+=3) {
                    int buf[9]={0}, *p=&buf[-1-'0'];
                    auto r0=&board[i][j], r1=&board[i+1][j], r2=&board[i+2][j];
                    for(int k=0;k<3;++k) {
                        if(r0[k]!='.') ++p[r0[k]];
                        if(r1[k]!='.') ++p[r1[k]];
                        if(r2[k]!='.') ++p[r2[k]];
                    }
                    for(p=&buf[0];p!=&buf[9];++p) if(*p>1) return false;
                }
            }
            return true;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.