脚本宝典收集整理的这篇文章主要介绍了PHP实现的数独求解问题示例,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
本文实例讲述了PHP实现的数独求解问题。分享给大家供大家参考,具体如下:
一、数独问题描述:
对于给出的数字二维数组,要求每行每列的数字不能重复。
二、实现代码:
<
PRe class="
brush:
PHp;">
clear();
} else {
$this->matrix = $arr;
}
}
function clear() {
for($i=0; $i<9; $i++)="" {="" for($j="0;">9;><9; $j++)="" {="" $this-="">matrix[$i][$j] = array();
for ($k = 1; $k <= 9;="" $k++)="" {="" $this-="">matrix[$i][$j][$k] = $k;
}
}
}
}
function setCell($row,$col,$value){
$this->matrix[$row][$col] = array($value => $value);
//row
for($i = 0; $i < 9;="" $i++){="" if($i="" !="$col){" if(!="" $this-="">removeValue($row,$i,$value)) {
return false;
}
}
}
//col
for($i = 0; $i < 9;="" $i++){="" if($i="" !="$row){" if(!="" $this-="">removeValue($i,$value)) {
return false;
}
}
}
//square
$rs=intval($row / 3) * 3;
$cs=intval($col / 3) * 3;
for($i = $rs; $i < $rs="" +="" 3;="" $i++){="" for($j="$cs;" $j="">< $cs="" +="" 3;="" $j++){="" if($i="" !="$row" &&="" $j="" !="$col){" if(!="" $this-="">removeValue($i,$j,$value))
return false;
}
}
}
return true;
}
function removeValue($row,$value) {
$count = count($this->matrix[$row][$col]);
if($count
== 1){
$ret = !isset($this->matrix[$row][$col][$value]);
return $ret;
}
if (isset($this->matrix[$row][$col][$value])) {
unset($this->matrix[$row][$col][$value]);
if($count - 1 == 1) {
return $this->setCell($row,
current($this->matrix[$row][$col]));
}
}
return true;
}
function set($arr) {
for ($i = 0; $i < 9;="" $i++)="" {="" for="" ($j="0;" $j="">< 9;="" $j++)="" {="" if="" ($arr[$i][$j]=""> 0) {
$this->setCell($i,$arr[$i][$j]);
}
}
}
}
function dump() {
for($i = 0; $i < 9;="" $i++){="" for($j="0;" $j="">< 9;="" $j++){="" $c="count($this-">matrix[$i][$j]);
if($c == 1){
echo " ".current($this->matrix[$i][$j])." ";
} else {
echo "(".$c.")";
}
}
echo "\n";
}
echo "\n";
}
function dumpAll() {
for($i = 0; $i < 9;="" $i++){="" for($j="0;" $j="">< 9;="" $j++){="" echo="" implode('',$this-="">matrix[$i][$j]),"\t";
}
echo "\n";
}
echo "\n";
}
function calc($data) {
$this->clear();
$this->set($data);
$this->_calc();
$this->dump();
}
function _calc() {
for($i = 0; $i < 9;="" $i++){="" for($j="0;" $j="">< 9;="" $j++){="" if(count($this-="">matrix[$i][$j]) == 1) {
continue;
}
for
each($this->matrix[$i][$j] as $v){
$flag = false;
$t = new Sudoku($this->matrix);
if(!$t->setCell($i,$v)){
continue;
}
if(!$t->_calc()){
continue;
}
$this->matrix = $t->matrix;
return true;
}
return false;
}
}
return true;
}
}
$sd=new Sudoku;
$sd->calc(array(
array(0,5,6,9,0),array(0,4,7,8,2,2),array(7,1,3,6),array(2,4),array(4,));
$sd->calc(array(
array(1,5),3),array(3,1),array(9,7),array(5,));
$sd->calc(array(
array(7,array(1,));
$sd->calc(array(
array(0,array(6,array(8,));
?>
=>9;>
脚本宝典总结
以上是脚本宝典为你收集整理的PHP实现的数独求解问题示例全部内容,希望文章能够帮你解决PHP实现的数独求解问题示例所遇到的问题。
如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。