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.

思路:

本题是解数独的入门级别的题目,仅仅是判断是否满足行列以及子方格数字的要求。

编写fill函数,isValid函数。

如果遇到  “.” ,继续;

如果不是先是判断能否满足,再就是更新。

代码:

class Solution {
public:
    int rowValid[9][10]={{0}};
    int colValid[9][10]={{0}};
    int subValid[9][10]={{0}};//0代表有效
    
    bool isValidSudoku(vector<vector<char>>& board) {
        for(int i=0;i<=8;i++){
            for(int j=0;j<=8;j++){
                if(board[i][j]=='.')
                    continue;
                int index=(int)(board[i][j]-'0');
                if( !isValid(i,j,index) )
                    return false;
                 fill(i,j,index);   
            }
        }
        return true;
    }
    
    bool isValid(int row,int col,int val){
        if(  rowValid[row][val]==0  && colValid[col][val]==0 && subValid[row/3*3+col/3][val]==0  )
            return true;
        return false;
    }
    
    void fill(int row,int col,int val){
        rowValid[row][val]=1;  
        colValid[col][val]=1;
        subValid[row/3*3+col/3][val]=1; 
    }
};


原文地址:https://www.cnblogs.com/jsrgfjz/p/8519822.html