首页 > 其他 > 详细

【Leetcode】Valid Sudoku

时间:2014-03-19 19:30:32      阅读:409      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     bool isValidSudoku(const vector<vector<char>>& board) {
 4         bool used[9];
 5         for (int i = 0; i < 9; ++i) {
 6             memset(used, false, 9);
 7             for (int j = 0; j < 9; ++j) {
 8                 if (board[i][j] == .) continue;
 9                 if (used[board[i][j] - 1]) {
10                     return false;
11                 } else {
12                     used[board[i][j] - 1] = true;
13                 }
14             }
15             memset(used, false, 9);
16             for (int j = 0; j < 9; ++j) {
17                 if (board[j][i] == .) continue;
18                 if (used[board[j][i] - 1]) {
19                     return false;
20                 } else {
21                     used[board[j][i] - 1] = true;
22                 }
23             }
24         }
25         for (int r = 0; r < 3; ++r) {
26             for (int c = 0; c < 3; ++c) {
27                 memset(used, false, 9);
28                 for (int i = 0; i < 3; ++i) {
29                     for (int j = 0; j < 3; ++j) {
30                         int v1 = r * 3 + i;
31                         int v2 = c * 3 + j;
32                         if (board[v1][v2] == .) continue;
33                         if (used[board[v1][v2] - 1]) {
34                             return false;
35                         } else {
36                             used[board[v1][v2] - 1] = true;
37                         }
38                     }
39                 }
40             }
41         }
42         return true;
43     }
44 };
View Code

依次检查即可,开始自作聪明想要在一个大的循环里面把三种方式都检查了,但是发现在检查小方块时下标运算会有除法和求模,反而使得程序变慢,另列一个3*3的循环虽然使代码变得复杂一点,但是思路清晰,且速度更快。

【Leetcode】Valid Sudoku,布布扣,bubuko.com

【Leetcode】Valid Sudoku

原文:http://www.cnblogs.com/dengeven/p/3611281.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!