1 2 3 4 5 6 7 8 9
32 33 34 35 36 37 38 39 10
31 56 57 58 59 60 61 40 11
30 55 72 73 74 75 62 41 12
29 54 71 80 81 76 63 42 13
28 53 70 79 78 77 64 43 14
27 52 69 68 67 66 65 44 15
26 51 50 49 48 47 46 45 16
25 24 23 22 21 20 19 18 17
$obj = new SpinningSnail();
$obj->run();
class SpinningSnail
{
public function run(){
$total = 9;
$result = array();
$x = $y = 1;
for ( $value = 1 ; $value <= ( $total * $total ) ;){
$this->recursiveProcessing($result, $x, $y, $value, $total);
}
for ($x= 1 ; $x<= $total ; $x ++ ){
for ( $y =1 ; $y <=$total;$y++ ){
echo $result[ $x ][ $y ] . "\t";
}
echo "\n";
}
echo "beautiful ~ ! \n";
}
public function recursiveProcessing ( &$result , &$x , &$y,&$value, &$total){
//先橫1
$this->crosswise( $result , $x , $y , $value , 1 , $total );
//在豎
$y --;
$x ++;
$this->portait( $result , $x , $y , $value , 1 , $total );
$y --;
$x --;
$this->crosswise( $result , $x , $y , $value , 2 , $total );
$y ++;
$x --;
$this->portait( $result , $x , $y , $value , 2 , $total );
$x ++;
$y ++;
return $result;
}
public function crosswise( &$result , &$x , &$y , &$value , $way = 1 , $total ){
$flag = true;
while ( $flag ){
if ( empty( $result[$x][ $y ] ) && ( $y <= $total ) && ( $y >= 1 ) ){
$result[ $x ][ $y ] = $value;
$value ++;
$y =( ( $way === 1 ) ? ($y + 1) : ( $y - 1 ) );
}else{
$flag = false;
}
}
return true;
}
public function portait( &$result , &$x , &$y , &$value , $way = 1 , $total ){
$flag = true;
while ( $flag ){
if ( empty( $result[$x][ $y ] ) && ( $x <= $total ) && ( $x >= 1) ){
$result[$x][ $y ] = $value;
$value ++;
$x = ( ( $way === 1 ) ? ($x+1) : ($x-1) );
}else{
$flag = false;
}
}
return true;
}
}
golang-版本-還有優(yōu)化空間
package arithmetic_test
import (
"strconv"
"testing"
)
func TestSnailArithmetic(t *testing.T) {
number := 10
t.Logf("輸出 %[1]d*%[1]d 的矩陣\n", number)
snail := snail(number)
//輸出
for _, rows := range snail {
s1 := ""
for _, col := range rows {
s1 = s1 + "\t" + strconv.Itoa(col)
}
t.Log(s1)
}
}
func snail(number int) [][]int {
var direction = [4][2]int{
{0, 1}, // 右
{1, 0}, // 下
{0, -1}, // 左
{-1, 0}, // 上
}
//初始化數(shù)據(jù)
snail := make([][]int, number)
for i := 0; i < number; i++ {
snail[i] = make([]int, number)
}
tag := 1
x := 0
y := 0
//循環(huán)處理數(shù)據(jù)
for {
//循環(huán)一圈的邏輯
for i := 0; i < 4; i++ {
snail, tag, x, y = pointerMovement(snail, direction[i], number, tag, x, y)
}
if tag > number*number {
break
}
}
return snail
}
func pointerMovement(snail [][]int, direction [2]int, number, tag int, x int, y int) ([][]int, int, int, int) {
for {
if tag > number*number {
break
}
if snail[x][y] <= 0 {
snail[x][y] = tag
tag++
if x+direction[0] < 0 || y+direction[1] < 0 || x+direction[0] >= number || y+direction[1] >= number || snail[x+direction[0]][y+direction[1]] > 0 {
break
} else {
x = x + direction[0]
y = y + direction[1]
}
} else {
x = x + direction[0]
y = y + direction[1]
}
}
return snail, tag, x, y
}