描述
螺旋数组
例子
Input:
7 9
Output:
1 2 3 4 5 6 7 8 9
28 29 30 31 32 33 34 35 10
27 48 49 50 51 52 53 36 11
26 47 60 61 62 63 54 37 12
25 46 59 58 57 56 55 38 13
24 45 44 43 42 41 40 39 14
23 22 21 20 19 18 17 16 15
思路
先将数组赋值为-1,使用一个变量记录当前方向(上下左右),当某个方向走不动时,换下一个方向。
代码
public class Question008 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int [][] array = new int [m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
array[i][j] = -1;
}
}
int x = 0, y = 0;
int count = 1;
// 右1 下2 左3 上4
int last_t = 1;
while (count <= m*n) {
array[x][y] = count++;
if(last_t == 1) {
if (y+1<n && array[x][y+1] < 0){
y++;
} else {
last_t = 2;
if (x+1 < m && array[x+1][y] < 0) {
x++;
}else {
break;
}
}
//下
} else if (last_t == 2) {
if(x+1 < m && array[x+1][y] < 0) {
x++;
} else {
last_t = 3;
if (y-1 >= 0 && array[x][y-1] < 0) {
y--;
} else {
break;
}
}
//左
} else if (last_t == 3) {
if(y-1 >= 0 && array[x][y-1] < 0) {
y--;
} else {
last_t = 4;
if (x-1 >= 0 && array[x-1][y] < 0) {
x--;
} else {
break;
}
}
}
//上
else {
if(x-1 >= 0 && array[x-1][y] < 0) {
x--;
} else {
last_t = 1;
if (y+1 < n && array[x][y+1] < 0) {
y++;
} else {
break;
}
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(array[i][j]+"\t");
}
System.out.println();
}
}
}