写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。如: n = 4 则打印:
1
| 2
| 3
| 4
| 12
| 13
| 14
| 5
| 11
| 16
| 15
| 6
| 10
| 9
| 8
| 7 |
- public class Test9 {
- static int cnt=0;
- static int[][] i = null;
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入要打印的等长二维数组长度");
- int nextInt = sc.nextInt();
- if (nextInt > 0) {
- i=new int[nextInt][nextInt];
- shuzu(i,0,nextInt);
- } else {
- System.out.println("请重新输入");
- }
- for (int k = 0; k < nextInt; k++) {
- for (int j = 0; j < nextInt; j++) {
- System.out.print(i[k][j]+"\t");
- }
- System.out.println();
- }
- }
- public static void shuzu(int[][] i, int start,int end) {
- if(end-start==1)
- {
- i[start][end-1]=++cnt;
- return;
- }
- if(start==end)
- return;
- for (int j = start; j < end-1; j++) {
- i[start][j]=++cnt;
- }
- for (int j = start; j < end-1; j++) {
- i[j][end-1]=++cnt;
- }
- for (int j = end-1; j >start; j--) {
- i[end-1][j]=++cnt;
- }
- for (int j = end-1; j >start; j--) {
- i[j][start]=++cnt;
- }
- shuzu(i,start+1,end-1);
- }
- }
复制代码 试着做了做了一下,感觉挺有意思的!希望多批评指点!
|
|