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

LeetCode: Valid Sudoku [035]

时间:2014-05-22 09:58:54      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】


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.



【题意】

判断一个数独是否合法。一个合法的数独要求:每行、每列、9个小九宫格中都只能填充1~9九个数字各一次。


【思路】

1. 为每一行建一个行访问标记数组
2. 为每一列建一个列访问标记数组
3. 为每个九宫格建一个访问标记数组
扫描数独矩阵,凡是有数字填充的在相应的访问数组中标记,如果发现有重复标记的,则返回false


【代码】

class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        vector<vector<bool> > rows(9, vector<bool>(9, false));
        vector<vector<bool> > cols(9, vector<bool>(9, false));
        vector<vector<bool> > blocks(9, vector<bool>(9, false));
        for(int i=0; i<9; i++){
            for(int j=0; j<9; j++){
                if(board[i][j]==‘.‘)continue;
                //判断行
                if(rows[i][board[i][j]-‘0‘-1])return false;
                else rows[i][board[i][j]-‘0‘-1]=true;
                //判断列
                if(cols[j][board[i][j]-‘0‘-1])return false;
                else cols[j][board[i][j]-‘0‘-1]=true;
                //判断block
                if(blocks[i/3*3+j/3][board[i][j]-‘0‘-1])return false;       //注意block索引号的计算
                else blocks[i/3*3+j/3][board[i][j]-‘0‘-1]=true;
            }
        }
        return true;
    }
};


LeetCode: Valid Sudoku [035],布布扣,bubuko.com

LeetCode: Valid Sudoku [035]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/26239443

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