Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 70b831d

Browse files
committed
Add solution 37.
1 parent 5eea853 commit 70b831d

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution {
2+
public function __construct() {
3+
$this->row = array_fill(0, 9, array_fill(0, 9, false));
4+
$this->col = array_fill(0, 9, array_fill(0, 9, false));
5+
$this->grid = array_fill(0, 9, array_fill(0, 9, false));
6+
$this->found = false;
7+
}
8+
9+
/**
10+
* @param String[][] $board
11+
* @return NULL
12+
*/
13+
function solveSudoku(&$board) {
14+
for ($i = 0; $i < 9; ++$i) {
15+
for ($j = 0; $j < 9; ++$j) {
16+
if ($board[$i][$j] != '.') {
17+
$this->row[$i][ord($board[$i][$j]) - ord('1')] = true;
18+
$this->col[$j][ord($board[$i][$j]) - ord('1')] = true;
19+
$this->grid[intval(($i / 3)) * 3 + intval(($j / 3)) % 3][ord($board[$i][$j]) - ord('1')] = true;
20+
}
21+
}
22+
}
23+
self::place(0, $board);
24+
return;
25+
}
26+
function place($n, &$board) {
27+
if ($n == 81) {
28+
// board = g;
29+
$this->found = true;
30+
return;
31+
}
32+
33+
$i = intval($n / 9); $j = $n % 9;
34+
$index = intval(($i / 3)) * 3 + intval(($j / 3)) % 3;
35+
if ($board[$i][$j] == '.') {
36+
for ($c = 0; $c < 9; ++$c) {
37+
if (!$this->row[$i][$c] && !$this->col[$j][$c] && !$this->grid[$index][$c]) {
38+
$this->row[$i][$c] = true;
39+
$this->col[$j][$c] = true;
40+
$this->grid[$index][$c] = true;
41+
$board[$i][$j] = chr($c + ord('1'));
42+
43+
self::place($n + 1, $board);
44+
45+
if ($this->found)
46+
return;
47+
48+
$board[$i][$j] = '.';
49+
$this->row[$i][$c] = false;
50+
$this->col[$j][$c] = false;
51+
$this->grid[$index][$c] = false;
52+
53+
}
54+
}
55+
}
56+
else
57+
self::place($n + 1, $board);
58+
return;
59+
}
60+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /