每日训练 -数独正确性

 1 /**
 2  * @param {character[][]} board
 3  * @return {boolean}
 4  */
 5 var isValidSudoku = function(board) {
 6      let index = 0,
 7       i = 0,
 8       returnVal = true,
 9       flag = 0,
10       itemIndex = 0,
11       newArr = [];
12     while (i < 9 && index < 9) {
13     //检查行
14       if (flag == 0) {
15         if (board[i][index] !== ".") {
16           newArr.push(board[i][index]);
17         }
18         index++;
19         if (index == 9) {
20           if(!checkRepeat(newArr)){
21               return false
22           }
23           index = 0;
24           i++;
25           newArr = [];
26         }
27         if (i == 9) {
28           flag = 1;
29           index = 0;
30           i = 0;
31           newArr = [];
32         }
33       }
34 
35     //检查列
36       if (flag == 1) {
37         if (board[i][index] !== ".") {
38           newArr.push(board[i][index]);
39         }
40         i++;
41         if (i == 9) {
42          if(!checkRepeat(newArr)){
43               return false
44           }
45           i = 0;
46           index++;
47           newArr = [];
48         }
49         if (index == 9) {
50           flag = 2;
51           index = 0;
52           i = 0;
53         }
54       }
55     //检查块
56       if (flag == 2) {
57         if (board[i][index] !== ".") {
58           newArr.push(board[i][index]);
59         }
60         index++;
61         if (index % 3 == 0 && (i + 1) % 3 == 0 && i !== 0 && index !== 0) {
62           if(!checkRepeat(newArr)){
63               return false
64           }
65           newArr = [];
66         }
67         if (i == 8 && index % 3 == 0) {
68           i = 0;
69           itemIndex = itemIndex + 3;
70           index = itemIndex;
71         } else if (index % 3 == 0) {
72           i++;
73           index = itemIndex;
74         }
75       }
76     }
77     return returnVal;
78 };
79 
80 //检查重复
81 var checkRepeat = function(Arr) {
82     let checkFlag = true
83     Arr.sort();
84     for (let j = 1; j < Arr.length; j++) {
85             if (Arr[j] - Arr[j-1] == 0) {
86               checkFlag = false
87             }
88           }
89     return checkFlag
90 }

跑了504个用例 全部通过, 用时110ms。

猜你喜欢

转载自www.cnblogs.com/syfnx/p/9066295.html