forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.php
75 lines (64 loc) · 1.58 KB
/
Solution.php
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
class Solution {
/**
* @param string[][] $board
* @return bool
*/
public function solveSudoku(&$board) {
if (isSolved($board)) {
return true;
}
$emptyCell = findEmptyCell($board);
$row = $emptyCell[0];
$col = $emptyCell[1];
for ($num = 1; $num <= 9; $num++) {
if (isValid($board, $row, $col, $num)) {
$board[$row][$col] = (string) $num;
if ($this->solveSudoku($board)) {
return true;
}
$board[$row][$col] = '.';
}
}
return false;
}
}
function isSolved($board) {
foreach ($board as $row) {
if (in_array('.', $row)) {
return false;
}
}
return true;
}
function findEmptyCell($board) {
for ($row = 0; $row < 9; $row++) {
for ($col = 0; $col < 9; $col++) {
if ($board[$row][$col] === '.') {
return [$row, $col];
}
}
}
return null;
}
function isValid($board, $row, $col, $num) {
for ($i = 0; $i < 9; $i++) {
if ($board[$row][$i] == $num) {
return false;
}
}
for ($i = 0; $i < 9; $i++) {
if ($board[$i][$col] == $num) {
return false;
}
}
$startRow = floor($row / 3) * 3;
$endCol = floor($col / 3) * 3;
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
if ($board[$startRow + $i][$endCol + $j] == $num) {
return false;
}
}
}
return true;
}