码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode - Valid Sudoku

时间:2014-10-25 17:27:30      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   ar   for   sp   on   

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 ‘.‘.

bubuko.com,布布扣

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 isValidSudoku(std::vector<std::vector<char> > &board) {
        int rows = board.size();
        int cols = board[0].size();
        int mask=0;
        int val;
        for(int i=0;i<rows;i++){
            mask=0;
            for(int j=0;j<cols;j++){
                if(board[i][j]!='.'){
                    int val = (int)(board[i][j]-'0');
                    if(mask & (1<<val))
                        return false;
                    else mask |= (1<<val);
                }
            }
        }
        //rows are checked
        for(int j=0;j<cols;j++){
            mask=0;
            for(int i=0;i<rows;i++){
                if(board[i][j]!='.'){
                    int val = (int)(board[i][j]-'0');
                    if(mask & (1<<val))
                        return false;
                    else mask |= (1<<val);
                }
            }
        }
        //cols are checked
        for(int i=0;i<rows;i+=3)
        {
            for(int j=0;j<cols;j+=3)
            {
                mask=0;
                for(int k=i;k<=i+2;k++)
                {
                    for(int l=j;l<=j+2;l++)
                    {
                        if(board[k][l]!='.'){
                            val = (int)(board[k][l]-'0');
                            if(mask&(1<<val))
                                return false;
                            else mask|=(1<<val);
                        }
                    }
                }
            }
        }
        return true;
    }
};


leetcode - Valid Sudoku

标签:style   http   color   io   os   ar   for   sp   on   

原文地址:http://blog.csdn.net/akibatakuya/article/details/40453417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!