数独 回溯算法

数独 回溯算法,计算未填写的 九宫格

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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class bord {
private $bord;

public function __construct(array $bord) {
$this->bord = $bord;
}


public function run() {
$pos = $this->next();
// var_dump($pos);
if ($pos == false) {
return true;
};
list($x, $y) = $pos;
// echo $this->string($x,$y);
// echo '<br/>';


for ($v = 1; $v < 10; $v++) {
// var_dump($x, $y, $v);
// var_dump($this->check($x, $y, $v));
//echo $this->__toString();
if ($this->check($x, $y, $v)) {
$this->set($x, $y, $v);
if($this->run()){
return true;
};

}


}
$this->release($x, $y);
// $this->run();

return false;




}

public function next() {
foreach ($this->bord as $x => $array) {
foreach ($array as $y => $v) {
if ($v == 0) {
return [$x, $y];
}
}
}
return false;
}

public function check($x, $y, $v) {
foreach ($this->bord as $x_a) {

if ($x_a[$y] == $v) {
return false;
}
}

foreach ($this->bord[$x] as $y_v) {
// var_dump($y_v);
if ($y_v == $v) {
return false;
}
}

$x_b = intval(floor(($x-1)/3)*3 +1);

$y_b = intval(floor(($y-1)/3)*3 +1);
// var_dump('x',$x_b);var_dump('y',$y_b);

for ($x = $x_b; $x < $x_b + 3; $x++) {
for ($y = $y_b; $y < $y_b + 3; $y++) {
if($this->bord[$x][$y] ==$v){
return false;
}
}
}

return true;
}

public function set($x, $y, $v) {
$this->bord[$x][$y] = $v;
}

public function complete() {
return $this->next() === false;
}

public function release($x, $y) {
$this->bord[$x][$y] = 0;
}
public function string($x_r=null,$y_r=null) {
$str = '';
foreach ($this->bord as $x => $array) {
foreach ($array as $y => $v) {
if($x_r && $y_r && $x_r==$x && $y_r==$y){
$str .= '<span style="color:red">'.$v . '</span>&nbsp; &nbsp; ';
}else{
$str .= $v . '&nbsp; &nbsp; ';
}


}
$str .= '<br/>';
}
return $str;

}
public function __toString() {
$str = '';
foreach ($this->bord as $x => $array) {
foreach ($array as $y => $v) {
$str .= $v . '&nbsp; &nbsp;';
}
$str .= '<br/>';
}
return $str;

}
}

$bord = new bord(array_fill(1,9,array_fill(1,9,0)));
$bord ->run();
echo $bord ;