$num = 10;
$arr = foo($num);
$arr =array_reverse($arr);
for ($i = 0 ;$i< $num;$i++){
echo $arr[$i] .PHP_EOL;
echo '<br>';
}
function foo($num){
//填充map
$data = new stdClass();
$data->x = 1;
$data->y = 1;
$data->num = $num;
$data->len = $num * $num;
$data->tmp_data = [];
$data->rate = 1;//方向
$data->struct = create_struct($num);
for ($i = $data->len;$i>=1;$i--){
$data->i = $i;
$key = change_key($data);
$data->tmp_data[$key] = $i;
unset($data->struct[$key]);
}
//根据y坐标分组
$data->struct = create_struct($num);
foreach ($data->tmp_data as $key=> $value){
$data->struct[$key]= $value;
}
for ($i=1;$i<=$data->num;$i++){
$start = ($i - 1)*$data->num;
$end = $data->num;
$slice = array_slice($data->struct,$start,$end);
$data->slice[] = '['.implode(",", $slice).']';
}
return $data->slice;
}
function change_key($data){
//check key
$key = $data->x.','.$data->y;
if(isset($data->struct[$key])){
return $key;
}
switch ($data->rate)
{
case 1:
//left
$data->tmp_x = $data->x + 1;
$key = $data->tmp_x.','.$data->y;
if(isset($data->struct[$key])){
$data->x = $data->tmp_x;
return $key;
}else{
$data->rate=2;
$data->y = $data->y+1;
}
break;
case 2:
//down
$data->tmp_y = $data->y + 1;
$key = $data->x.','.$data->tmp_y;
if(isset($data->struct[$key])){
$data->y = $data->tmp_y;
return $key;
}else{
$data->rate=3;
}
break;
case 3:
//right
$data->tmp_x = $data->x - 1;
$key = $data->tmp_x.','.$data->y;
if(isset($data->struct[$key])){
$data->x = $data->tmp_x;
return $key;
}else{
$data->rate=4;
}
break;
case 4:
//up
$data->tmp_y = $data->y - 1;
$key = $data->x.','.$data->tmp_y;
if(isset($data->struct[$key])){
$data->y = $data->tmp_y;
return $key;
}else{
$data->rate=1;
}
break;
}
return change_key($data);
}
function create_struct($num){
$struct = [];
for ($i=1;$i<=$num;$i++){
//嵌套
for($m=1;$m<=$num;$m++){
$key = $m . ','. $i;
$struct[$key] = '';
}
}
return $struct;
}
function dump($data){
echo '<pre>';
print_r($data);
echo '</pre>';
echo '<br>';
}
输出结果
[73,74,75,76,77,78,79,80,81,82]
[72,43,44,45,46,47,48,49,50,83]
[71,42,21,22,23,24,25,26,51,84]
[70,41,20,7,8,9,10,27,52,85]
[69,40,19,6,1,2,11,28,53,86]
[68,39,18,5,4,3,12,29,54,87]
[67,38,17,16,15,14,13,30,55,88]
[66,37,36,35,34,33,32,31,56,89]
[65,64,63,62,61,60,59,58,57,90]
[100,99,98,97,96,95,94,93,92,91]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。