36. 有效的数独

一、题目原型:

判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

二、题目意思剖析:

1
2
3
4
5
6
7
8
9
10
11
12
13
输入:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
输出: true

三、解题思路:

数独,应该大家都玩过,其实就只是判断三个点,横、竖、3*3的方格。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
func isValidSudoku(_ board: [[Character]]) -> Bool {

var bool: Bool = true

for i in 0..<board.count {

let characters = board[i]
var mutCharacters1: [Character] = []
var mutCharacters2: [Character] = []
for j in 0..<characters.count {

// 1.每行比较
let character1 = board[i][j]
if character1 != "." {
mutCharacters1.append(character1)
}

// 2.每列比较
let character2 = board[j][i]
if character2 != "." {
mutCharacters2.append(character2)
}

if j == characters.count - 1 {

let set1: Set = Set(mutCharacters1)
if set1.count == mutCharacters1.count {
bool = true
}else {
bool = false
return bool
}

let set2: Set = Set(mutCharacters2)
if set2.count == mutCharacters2.count {
bool = true
}else {
bool = false
return bool
}
}
}
}

var index_i = 0
var index_j = 0
while index_i<board.count {

// 3.每方格
while index_j<board[0].count {

var square: [Character] = []
if board[index_i][index_j] != "." {
square.append(board[index_i][index_j])
}
if board[index_i+1][index_j] != "." {
square.append(board[index_i+1][index_j])
}
if board[index_i+2][index_j] != "." {
square.append(board[index_i+2][index_j])
}
if board[index_i][index_j+1] != "." {
square.append(board[index_i][index_j+1])
}
if board[index_i+1][index_j+1] != "." {
square.append(board[index_i+1][index_j+1])
}
if board[index_i+2][index_j+1] != "." {
square.append(board[index_i+2][index_j+1])
}
if board[index_i][index_j+2] != "." {
square.append(board[index_i][index_j+2])
}
if board[index_i+1][index_j+2] != "." {
square.append(board[index_i+1][index_j+2])
}
if board[index_i+2][index_j+2] != "." {
square.append(board[index_i+2][index_j+2])
}

if index_j % 3 == 0 {
let set: Set = Set(square)
if set.count == square.count {
bool = true
}else {
bool = false
return bool
}
}
// 因为是3*3的小方格,所以需要+3,而不是再+1了
index_j = index_j + 3
}
index_i = index_i + 3
// 因为index_j循环后变成了9,需要设置为0
index_j = 0
}
return bool
}

四、小结

耗时72毫秒,超过73.77%的提交记录,总提交数504

坚持原创技术分享,您的支持将鼓励我继续创作!