[Leetcode] Valid Sudoku

[Leetcode] Valid Sudoku
强烈推介IDEA2021.1.3破解激活,IntelliJ IDEA 注册码,2021.1.3IDEA 激活码  

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说[Leetcode] Valid Sudoku,希望能够帮助大家进步!!!

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

[Leetcode] Valid Sudoku

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.

没啥算法,纯模拟!

 1 class Solution {
 2 public:
 3     bool isValidCell(vector<vector<char> > &board, int a, int b) {
 4         vector<bool> flag(9, false);
 5         int idx;
 6         for (int i = 0; i < 3; ++i) {
 7             for (int j = 0; j < 3; ++j) {
 8                 idx = board[a + i][b + j] - '0';
 9                 if (idx > 0 && idx <= 9 && !flag[idx])  
10                     flag[idx] = true;
11                 else if (idx > 0 && idx <= 9 && flag[idx])
12                     return false;
13             }
14         }
15         return true;
16     }
17     
18     bool isValidRow(vector<vector<char> > &board, int a) {
19         vector<bool> flag(9, false);
20         int idx;
21         for (int j = 0; j < 9; ++j) {
22             idx = board[a][j] - '0';
23             if (idx > 0 && idx <= 9 && !flag[idx])  
24                 flag[idx] = true;
25             else if (idx > 0 && idx <= 9 && flag[idx])
26                 return false;
27         }
28         return true;
29     }
30     
31      bool isValidCol(vector<vector<char> > &board, int b) {
32         vector<bool> flag(9, false);
33         int idx;
34         for (int i = 0; i < 9; ++i) {
35             idx = board[i][b] - '0';
36             if (idx > 0 && idx <= 9 && !flag[idx])  
37                 flag[idx] = true;
38             else if (idx > 0 && idx <= 9 && flag[idx])
39                 return false;
40         }
41         return true;
42     }
43     
44     bool isValidSudoku(vector<vector<char> > &board) {
45         for (int i = 0; i < 3; ++i) {
46             for (int j = 0; j < 3; ++j) {
47                 if (!isValidCell(board, 3 * i, 3 * j)) 
48                     return false;
49             }
50         }
51         for (int i = 0; i < 9; ++i) {
52             if (!isValidRow(board, i))
53                 return false;
54         }
55         for (int j = 0; j < 9; ++j) {
56             if (!isValidCol(board, j))
57                 return false;
58         }
59         return true;
60     }
61 };

 

转载于:https://www.cnblogs.com/easonliu/p/3662684.html

本文来源weixin_30595035,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/29639

发表评论