Jack Li's Blog

0036.Valid Sudoku

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int m = board.size();
        int n = board[0].size();

        int columnMap[9][9];
        int rowMap[9][9];
        int threeMap[9][9];

        memset(rowMap, 0, sizeof(rowMap));
        memset(columnMap, 0, sizeof(columnMap));
        memset(threeMap, 0, sizeof(threeMap));

        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(isdigit(board[i][j])) {
                    int idx = board[i][j] - '1';

                    // columnMap
                    if(columnMap[j][idx] != 0) return false;
                    columnMap[j][idx] = 1;

                    // rowMap
                    if(rowMap[i][idx] != 0) return false;
                    rowMap[i][idx] = 1;

                    // threeMap
                    int threeIdx = i/3 * 3 + j/3;
                    if(threeMap[threeIdx][idx] != 0) return false;
                    else threeMap[threeIdx][idx] = 1;
                }
            }
        }

        return true;
    }
};