-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCh1_8.java
More file actions
91 lines (86 loc) · 2.74 KB
/
Copy pathCh1_8.java
File metadata and controls
91 lines (86 loc) · 2.74 KB
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
public class Ch1_8
{
static int length = 8;
static int value = 1;
static int[][] snake = new int[length][length];
static Direction lastDirection = Direction.Right;
static enum Direction
{
Right, Down, Left, Up;
}
//按顺时针,从外向内,填充数字
public static void initialArray()
{
int row = 0, col = 0;
for (int c = 0; c < length * length; c++)
{
snake[row][col] = value; //当前位置赋值
lastDirection = findDirection(row, col); //寻找下一步方向
switch (lastDirection) {
case Right:
col++; //如果向右,列加1
break;
case Down:
row++; //如果向下,行加1
break;
case Left:
col--; //如果向左,列减1
break;
case Up:
row--; //如果向上,行减1
break;
default:
System.out.println("error");
}
value++; //下一个数字
}
}
//根据当前方向,结合当前位置,确定下一步方向
static Direction findDirection(int row, int col)
{
Direction direction = lastDirection;
switch (direction) {
case Right: {
//如果到右边界或者当前位置右方已经填充过数字,则转弯向下
if ((col == length - 1) || (snake[row][col + 1] != 0))
direction = direction.Down;
break;
}
case Down: {
//如果到下边界或者当前位置下方已经填充过数字,则转弯向左
if ((row == length - 1) || (snake[row + 1][col] != 0))
direction = direction.Left;
break;
}
case Left: {
//如果到左边界或者当前位置左方已经填充过数字,则转弯向上
if ((col == 0) || (snake[row][col - 1] != 0))
direction = direction.Up;
break;
}
case Up: {
//如果当前位置上方已经填充过数字,则转弯向右
if (snake[row - 1][col] != 0)
direction = direction.Right;
break;
}
}
return direction;
}
static void print(int[][] arr)
{
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
System.out.printf(" %2d",arr[i][j]);
}
System.out.println();
}
}
public static void main(String[] args)
{
initialArray(); //填充数字
print(snake); //输出
}
}