[LeetCode] [数独问题] Valid Sudoku

2014-11-24 07:10:45 · 作者: · 浏览: 0

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.

问题描述:判断一个数独是否是合法的。

按实际来说,合法的数独应该只有唯一解,不过,这里只考虑数独满足的性质,即它的行、列、宫所满足的条件。

因此,就可以直接借用Sudoku Solver的部分代码,然后依次判断每个元素是否合法,只要有一个不合法,就说明该数独不合法。

class Solution {
public:
    static const int MAXN = 9;
    static const int TRI = 3;

    void get_next(int ln, int col, int &next_ln, int &next_col)
    {
        if(!((ln + 1) % TRI) && !((col + 1) % TRI)) {
            if(ln + 1 == MAXN && col + 1 == MAXN) {
                next_ln = ln + 1;
                next_col = col + 1;
            }
            else if(ln + 1 != MAXN && col + 1 == MAXN) {
                next_ln = ln + 1;
                next_col = 0;
            }
            else {
                next_ln = ln - 2;
                next_col = col + 1;
            }
        }
        else if(((ln + 1) % TRI) && !((col + 1) % TRI)) {
            next_ln = ln + 1;
            next_col = col - 2;
        }
        else {
            next_ln = ln;
            next_col = col + 1;
        }
    }

    int in_square(vector
  
    > &board, int ln, int col, char digit)
    {
        int s_ln = (ln / TRI) * TRI, s_col = (col / TRI) * TRI;
        int next_ln = 0, next_col = 0;
        int cnt = 9;

        while(cnt--) {
            if(board[s_ln][s_col] == digit && s_ln != ln && s_col != col)
                return 1;
            get_next(s_ln, s_col, next_ln, next_col);
            s_ln = next_ln;
            s_col = next_col;
        }

        return 0;
    }

    int is_valid(vector
   
     > &board, int ln, int col, char digit) { int i = 0; for(i = 0; i < MAXN; ++i) { if(board[i][col] == digit && i != ln || board[ln][i] == digit && i != col) { return 0; } } return 1; } bool isValidSudoku(vector
    
      > &board) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int i = 0, j = 0; for(i = 0; i < MAXN; ++i) { for(j = 0; j < MAXN; ++j) { if(board[i][j] != '.' && (in_square(board, i, j, board[i][j]) || !is_valid(board, i, j, board[i][j]))) return false; } } return true; } };