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
| <?php
// example
$a = array(
array( 1 , 2 , 3 , 4 , 5 , 6 , 7 ),
array( 24, 25, 26, 27, 28, 29, 8 ),
array( 23, 40, 41, 42, 43, 30, 9 ),
array( 22, 39, 48, 49, 44, 31, 10),
array( 21, 38, 47, 46, 45, 32, 11),
array( 20, 37, 36, 35, 34, 33, 12),
array( 19, 18, 17, 16, 15, 14, 13));
$total = 49;
$root = 7;
$y = 0;
$x = 0;
$move = 'right';
$b = array();
for( $i = 1; $i <= $total; $i++ ) {
calc($i);
}
echo '<pre>';
print_r($b);
echo '</pre>';
function calc( $i ) {
global $b,$x,$y,$move,$total,$root;
if( ( ! isset( $b[$y][$x] ) ) && ( $y < $root ) && ( $x < $root ) ) { // first
$b[$y][$x] = $i;
} else {
// move
if( $move == 'right' ) {
if( ( ! isset( $b[$y][$x+1 ) ) && ( ($x+1) < $root) ) {
$b[$y][$x+1] = $i;
$x = $x+1;
} else {
$move = 'down';
calc($i);
}
} elseif( $move == 'down' ) {
if( ( ! isset( $b[$y+1][$x] ) ) && ( ($y+1) < $root) ) {
$b[$y+1][$x] = $i;
$y = $y+1;
} else {
$move = 'left';
calc($i);
}
} elseif( $move == 'left' ) {
if( ( ! isset( $b[$y][$x-1] ) ) && ( ! $x < -1) ) {
$b[$y][$x-1] = $i;
$x = $x-1;
} else {
$move = 'up';
calc($i);
}
} elseif( $move == 'up' ) {
if( ( ! isset( $b[$y-1][$x] ) ) && ( ! $y < -1) ) {
$b[$y-1][$x] = $i;
$y = $y-1;
} else {
$move = 'right';
calc($i);
}
}
}
}
?> |