题目描述:

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

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

题意大致为:给我们一个九宫格,让我们验证这个九宫格是对是错。九宫格可以是没填满的,没填满的部分用 '.' 代替。

解题思路:

解这题我主要从九宫格的规则出发:

  1. 每行数字不能重复;
  2. 每列数字不能重复;
  3. 九个区域中每个区域的数字不能重复。

根据这三条规则我把第一天和第二条整合在一起写出了两个验证子函数。

代码:

 1 class Solution {
 2 public:
 3     bool isValidRowsCols(vector<vector<char>>& board, int num){
 4     //行和列的验证
 5         if(num == 9)
 6             return true;
 7         vector<int> oneRow(58, 0), oneCol(58, 0);//因为'9'的十进制为57,所以只要58个数就行了
 8         for(int i=0; i<9; i++){
 9             if(++oneRow[board[num][i]]>1&&board[num][i]!='.')
10             //这里是用字符做下标进行记录的
11                 return false;
12             if(++oneCol[board[i][num]]>1&&board[i][num]!='.')
13                 return false;
14         }
15         return isValidRowsCols(board, num+1);
16     }
17     bool isValidNine(vector<vector<char>>& board, int row, int col){
18     //每个区域的验证
19         if(row == 9 || col == 9)
20             return true;
21         vector<int> nine(58,0);
22         for(int i = row; i < row+3;i++){
23             for(int j = col; j < col+3; j++){
24                 if(++nine[board[i][j]]>1&&board[i][j]!='.')
25                     return false;
26             }
27         }
28         return isValidNine(board, row+3, col) && isValidNine(board, row, col+3);//这里分别是验证下移和右移一个区域是否有效,两个都有效返回true
29     }
30     bool isValidSudoku(vector<vector<char>>& board) {
31         return isValidNine(board, 0, 0) && isValidRowsCols(board, 0);
32     }
33 };

 

 

 

posted on 2018-02-28 00:26  宵夜在哪  阅读(105)  评论(0编辑  收藏  举报