36. Valid Sudoku

来源:互联网 发布:程序员联合开发网会员 编辑:程序博客网 时间:2024/06/15 16:05

题目

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.

分析

9*9数独要求满足同一行、同一列、同一宫(3*3)内不能有重复数字,因此对本题中的已知的部分数字进行这一规则的判断即可,不用求出数独的解。

class Solution {public:    bool isValidSudoku(vector<vector<char>>& board) {        bool row[9][9]={0},col[9][9]={0},sqr[9][9]={0};//分别保存同一行,同一列,同一个宫里面已知数的计数        for(int i=0;i<9;i++)        {            for(int j=0;j<9;j++)            {                char c=board[i][j];                if(c!='.')                {                    if(row[i][c%9]++)//对同一行数按模9来区分,使用后缀加,当第一次遇到该数时,使用原值0判断,不会进入循环并在之后执行+1操作                        return false;//若是第二次,则用1判断,说明同一行有两个相同元素,返回false                    if(col[j][c%9]++)                        return false;                    if(sqr[(i/3)*3+j/3][c%9]++)//按照3*3矩阵分成九个宫,记录每个宫内已知数的个数                        return false;                }            }        }        return true;    }};


0 0
原创粉丝点击