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.

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int n = board.size();
        if (n == 0) return false;
        int m = board[0].size();
        for (int i = 0; i < n; ++i) {
            if (!validRow(board[i])) {
                return false;
            }
        }
        for (int i = 0; i < n; ++i) {
            if (!validCol(board, i)) {
                return false;
            } 
        }
        for (int i = 0; i < n; i += 3) {
            for (int j = 0; j < m; j += 3) {
                if (!validCell(board, i, j)) {
                    return false;
                }
            }
        }
        return true;
    }

private:
    bool validRow(vector<char>& row) {
        vector<bool> visited(10, false);
        for (char c : row) {
            if (!valid(visited, c)) {
                return false;
            }
        }
        return true;
    }

    bool validCol(vector<vector<char>>& board, int col) {
        vector<bool> visited(10, false);
        for (int i = 0; i < board.size(); ++i) {
            char c = board[i][col];
            if (!valid(visited, c)) {
                return false;
            }
        }
        return true;
    }

    bool validCell(vector<vector<char>>& board, int startRow, int startCol) {
        vector<bool> visited(10, false);
        for (int i = startRow; i < startRow + 3; ++i) {
            for (int j = startCol; j < startCol + 3; ++j) {
                char c = board[i][j];
                if (!valid(visited, c)) {
                    return false;
                } 
            }
        }
        return true;
    }

    bool valid(vector<bool>& visited, char c) {
        if (c != '.') {
            if (visited[c - '1']) {
                return false;
            } else {
                visited[c - '1'] = true;
            }
        }
        return true;
    }
};

results matching ""

    No results matching ""