[leetcode]Valid Sudoku

Valid Sudoku

  Total Accepted: 4716  Total Submissions: 17442 My Submissions

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 AnyRect(vector<vector<char>> &board, int x1,int y1,int x2,int y2){
        vector<int> map(256,0);
        for(int row=x1; row<=x2; row ++){
            for(int col=y1; col <=y2; col ++){
                int ch=board[row][col];
                if(ch <= '9' && ch >='1'){
                    if(map[ch]!=0)
                        return false;
                    map[ch]++;
                }
                else if(ch!='.')
                    return false;
            }
        }
        return true;
    }
    
    bool checkRowAndCol(vector<vector<char> > &board){
        for(int col=0; col<9; col++){ //检查每行
            if(AnyRect(board, 0,col,8,col)==false)
                return false;
        }
        for(int row=0; row<9; row++){ //检查每列
            if(AnyRect(board,row,0,row,8)==false)
                return false;
        }
        return true;
    }
    
    bool checkGrid(vector<vector<char>> &board){
        for(int gridrow=0; gridrow<3; gridrow++){
            for(int gridcol=0; gridcol<3; gridcol++){
                int row1=gridrow*3;
                int row2=row1+2;
                int col1=gridcol*3;
                int col2=col1+2;
                if(AnyRect(board,row1,col1,row2,col2)==false)
                    return false;
            }
        }
        return true;
    }
    bool isValidSudoku(vector<vector<char> > &board) {  
        return checkRowAndCol(board) && checkGrid(board);  
    }  
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值