从键盘输入一个整数(1~20)

则以该数字为矩阵的大小,把 1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。例如:

输入数字 2,则程序输出:

1 2

4 3

输入数字 3,则程序输出:

1 2 3

8 9 4

7 6 5

输入数字 4, 则程序输出:

1 2 3 4

12 13 14 5

11 16 15 6

10 9 8 7

package Question20_29;

import java.util.Scanner;

public class Question25 {

public static void print(int[][] array) {

for (int i = 0; i < array.length; i++) {

for (int j = 0; j < array.length; j++) {

System.out.printf("%4d",array[i][j]);

}

System.out.println();

}

}

public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);

int n=scanner.nextInt();

48

int array[][]=new int[n][n];

int startIndex=0,endIndex=n-1,count=1,e=0;

while (e<=n/2) {

for (int i = startIndex; i <= endIndex; i++) {

array[e][i]=count++;

}

for (int i = startIndex+1; i <= endIndex; i++) {

array[i][n-1-e]=count++;

}

for (int i = endIndex-1; i>=startIndex; i--) {

array[n-1-e][i]=count++;

}

for (int i = endIndex-1; i>startIndex; i--) {

array[i][e]=count++;

}

startIndex++;

endIndex--;

e++;

}

print(array);

}

}

运行结果:

输入一个整数:4

1 2 3 4

12 13 14 5

11 16 15 6

10 9 8 7

整体思路: (外圈实现:

从(左->右)填充第一行

2.从(上->下)填充右侧一列

49

3.从(右->左)填充最后一行

4.从(下->上)填充左侧一列

public class Demo08_two {

public static void show(int[][] m) {

for (int[] x : m) {

for (int y : x) {

System.out.print(y + "\t");

}

System.out.println("");

}

}

public static void helix(int n, int b, int[][] a) {

int i;

int j;

int k;

for (i = 0; i < n / 2; i++) {

for (j = i; j < n - i; j++)

/* 四个循环按不同的方向进行 */

a[i][j] = ++b;

for (k = i + 1, j--; k < n - i; k++)

a[k][j] = ++b;

for (j = --k, j--; j >= i; j--)

a[k][j] = ++b;

for (k--; k > i; k--)

a[k][i] = ++b;

}

if (n % 2 != 0) /* 如果是单数的话,要加上最大的那个数放在中间 */

a[i][i] = ++b;

}

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

int i, j, k, n, b = 0;

System.out.print("输入一个整数:");

n = scan.nextInt();

int[][] a = new int[n][n];

helix(n, b, a);

show(a);

}

}

运行结果:

输入一个整数:4

1 2 3 4

12 13 14 5

11 16 15 6

10 9 8 7

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐