Home > php教程 > PHP源码 > body text

PHP穷举法列出三阶幻方(九宫格)的解

PHP中文网
Release: 2016-05-25 17:07:08
Original
1902 people have browsed it

<?php
ignore_user_abort(true);
set_time_limit(0);
$tmp = array();
function getArr($arr=&#39;&#39;)
{
 for ($i = 1; $i <= 9; $i++) {
 if ( empty($arr) ) {
 $arr[] = $i;
 } elseif ( in_array($i, $arr) ) {
continue;
 } else {
 $arr[] = $i;
}
 if ( count($arr) < 9 ) {
getArr($arr);
}
 if ( count($arr) < 9 && count($arr) > 1 ) {
array_pop($arr);
continue;
 } elseif ( count($arr) == 1 ) {
unset($arr);
continue;
 } elseif ( checkArr($arr) ) {
 $GLOBALS[&#39;tmp&#39;][] = $arr;
}
}
}
function checkArr($arr)
{
 $m = array();
 $m[] = $arr[0] + $arr[1] + $arr[2];
 $m[] = $arr[3] + $arr[4] + $arr[5];
 $m[] = $arr[6] + $arr[7] + $arr[8];
 $m[] = $arr[0] + $arr[3] + $arr[6];
 $m[] = $arr[1] + $arr[4] + $arr[7];
 $m[] = $arr[2] + $arr[5] + $arr[8];
 $m[] = $arr[0] + $arr[4] + $arr[8];
 $m[] = $arr[2] + $arr[4] + $arr[6];
 $tmp = array_count_values($m);
 foreach ($tmp as $v) {
 if ( $v == 8 ) {
 return true;
 } else {
 return false;
}
}
}
$startTime = microtime(true);
getArr();
$endTime = microtime(true);
for( $i=0; $i<count($tmp); $i++ ) {
$arr = $tmp[$i];
echo $str=<<<fs
 <table border="1"style="float:left;margin-left:10px;">
<tr>
<td>{$arr[0]}</td>
<td>{$arr[1]}</td>
<td>{$arr[2]}</td>
</tr>
<tr>
<td>{$arr[3]}</td>
<td>{$arr[4]}</td>
<td>{$arr[5]}</td>
</tr>
<tr>
<td>{$arr[6]}</td>
<td>{$arr[7]}</td>
<td>{$arr[8]}</td>
</tr>
</table>
fs;
}
echo &#39;<div style="float:left;width:100%;height:5px;clear:both"></div><h1 style="float:left">共花费时间:&#39;;
echo round($endTime - $startTime, 3);
echo &#39;秒</h1>&#39;;
die;
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template