leetcode-- Valid Sudoku

来源:互联网 发布:淘宝买家秀木耳图链接 编辑:程序博客网 时间:2024/06/15 12:35

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
There are just 3 rules to Sudoku.
Each row must have the numbers 1-9 occuring just once.

Each column must have the numbers 1-9 occuring just once.

And the numbers 1-9 must occur just once in each of the 9 sub-boxes of the grid.

The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.

这里写图片描述

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

解:

只循环一次就能检测出结果,生成3个同样大小的bool数组保存检测到的数字,used1 保存每一行中看到的数字,used2 保存每一列,used3保存每一个subblock

class Solution{public:    bool isValidSudoku(vector<vector<char> > &board)    {        int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0};        for(int i = 0; i < board.size(); ++ i)            for(int j = 0; j < board[i].size(); ++ j)                if(board[i][j] != '.')                {                    int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3;                    if(used1[i][num] || used2[j][num] || used3[k][num])                        return false;                    used1[i][num] = used2[j][num] = used3[k][num] = 1;                }        return true;    }};
0 0
原创粉丝点击