Leetcode: Valid Sudoku

来源:互联网 发布:java 开源工作流 编辑:程序博客网 时间:2024/05/08 09:24

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.

判断数独是否合法,一个个的扫描,行、列、格子即可。

class Solution {public:    bool isValidSudoku(vector<vector<char> > &board) {        int size = board.size();        pair<int, int> points[] = {{0, 0,}, {0, 3}, {0, 6}, {3, 0}, {3, 3}, {3, 6}, {6, 0}, {6, 3}, {6, 6}};                for (int i = 0; i < size; ++i) {            vector<int> row_count(size, 0);            vector<int> col_count(size, 0);            vector<int> box_count(size, 0);            for (int j = 0; j < size; ++j) {                if (board[i][j] != '.') {                    if (++row_count[board[i][j] - '1'] > 1) {                        return false;                    }                }                if (board[j][i] != '.') {                    if (++col_count[board[j][i] - '1'] > 1) {                        return false;                    }                }                int px = points[i].first + j / 3;                int py = points[i].second + j % 3;                if (board[px][py] != '.') {                    if (++box_count[board[px][py] - '1'] > 1) {                        return false;                    }                }            }        }                return true;    }};

0 0