leetcode 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 '.'.
1

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.

嗯,老题目了。定义一个row[9][9]记录第i行j出现了几次,定义一个col[9][9]记录第i列j出现了几次,定义sq[9][9]记录第i个方块j出现了几次。

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        array<array<int, 10>, 10> row = {0};
        array<array<int, 10>, 10> col = {0};
        array<array<int, 10>, 10> sq = {0};
        for (int i = 1; i <= 9; ++i) {
            for (int j = 1; j <= 9; ++j) {
                if (board[i-1][j-1]!= '.') {
                    int a = board[i-1][j-1]-'0';
                    row[i][a] ++;
                    col[j][a] ++;
                    int x = (i-1)/3*3+(j-1)/3;
                    sq[x][a] ++;
                }
            }
        }
        int mark = 0;
        for (int i = 1; i <= 9; ++i) {
            for (int j = 1; j <= 9; ++j) {
                if (col[i][j] >= 2 || row[i][j] >= 2 || sq[i-1][j] >= 2) {
                    mark = 1; break;
                }
            }
            if (mark) break;
        }
        if (mark) return false;
        return true;
    }
};
posted on 2017-10-20 14:37  Beserious  阅读(102)  评论(0编辑  收藏  举报