黑马程序员技术交流社区
标题:
入学试题:二位数组螺旋式打印 求讲解
[打印本页]
作者:
qimingxue
时间:
2014-4-26 15:40
标题:
入学试题:二位数组螺旋式打印 求讲解
写一方法,打印等长的二维数组,要求从
* 1开始的自然数由方阵的最外圈向内螺旋方式地顺
* 序排列。 如: n = 4 则打印:
* 1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
作者:
二小傻
时间:
2014-4-26 16:01
package test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("请输入数字:");
Scanner s = new Scanner(System.in);
Integer i = s.nextInt();
int[][] matrix = new int[i][i];
int max = i * i;
int row = 0, col = 0;
int direction = 0;
for (int j = 1; j <= max; j++) {
matrix[row][col] = j;
switch (direction) {
case 0:
if (col + 1 >= i || matrix[row][col + 1] > 0) {
direction += 1;
direction %= 4;
row += 1;
} else {
col = col + 1;
}
break;
case 1:
if (row + 1 >= i || matrix[row + 1][col] > 0) {
direction += 1;
direction %= 4;
col -= 1;
} else {
row = row + 1;
}
break;
case 2:
if (col - 1 < 0 || matrix[row][col - 1] > 0) {
direction += 1;
direction %= 4;
row = row - 1;
} else {
col = col - 1;
}
break;
case 3:
if (row - 1 < 0 || matrix[row - 1][col] > 0) {
direction += 1;
direction %= 4;
col += 1;
} else {
row = row - 1;
}
break;
default:
System.out.println("ERROR");
System.exit(0);
}
}
for (int j = 0; j < i; j++) {
for (int k = 0; k < i; k++) {
if (matrix[j][k] < 10)
System.out.print(" " + matrix[j][k]);
else
System.out.print(" " + matrix[j][k]);
}
System.out.println("");
}
}
}
复制代码
作者:
Ice丶wj
时间:
2014-6-13 12:21
二小傻 发表于 2014-4-26 16:01
太厉害了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2