Leetcode -- Valid Sudoku

来源:互联网 发布:网络语企鹅是什么意思 编辑:程序博客网 时间:2024/05/16 06:53

题目:
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 isValidSudoku(vector<vector<char>>& board) {        vector< vector<int> > arr(10, vector<int>(10, 0));        vector<vector<int>> smallArr(10, vector<int>(10, 0));        vector<vector<int>> col(10, vector<int>(10, 0));        int num;        for(int i = 0; i<= 6; i = i + 3)        {            for(int j = 0; j<= 6; j = j + 3)            {                for(int a = 0; a< 3; a++)                {                    for(int b =0; b<3; b++)                    {                        if(board[i+a][j+b] != '.')                        {                            num = board[i+a][j+b] - '0';                            arr[i +a][num] ++;                            smallArr[i + j/3][num] ++;                            col[j + b][num] ++;                            if(arr[i+a][num] > 1 || smallArr[i + j/3][num]> 1 || col[j + b][num] > 1)                            {                                return false;                            }                        }                    }                }            }        }        return true;    }};

注意:
下标什么时候结束的问题。第一次刷的时候,下标的边界弄错了,调试了好久,sad!
一旦涉及到循环,下标的边界一定要好好检查一下。

0 0
原创粉丝点击