java 的编程
从键盘输入一个整数(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
import java.util.Scanner; public class SpiralMatrix { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int width = 1 + (int) Math.log10(n * n); int matrix[][] = new int[n][n]; int count = 1; for (int i = n - 1, j = 0; i > 0; --i, ++j) { for (int k = j; k < i; ++k) matrix[j][k] = count++; for (int k = j; k < i; ++k) matrix[k][i] = count++; for (int k = i; k > j; --k) matrix[i][k] = count++; for (int k = i; k > j; --k) matrix[k][j] = count++; } if ((n & 1) != 0) matrix[(n - 1) >> 1][(n - 1) >> 1] = count++; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { System.out.format("%" + width + "d ", matrix[i][j]); } System.out.println(); } } }
import java.util.Scanner; public class Snake { public static void snake(int n, int rows, int cols, int count, int[][] s) { int x = 0, y = 0; if(n <= 1) { if(n == 1) s[rows][cols] = count++; return; } while(y < n - 1) s[rows + x][cols + y++] = count++; while(x < n - 1) s[rows + x++][cols + y] = count++; while(cols + y > cols) s[rows + x][cols + y--] = count++; while(rows + x > rows) s[rows + x--][cols + y] = count++; snake(n - 2, rows + 1, cols + 1, count, s); } public static void main(String[] args) { Scanner reader = new Scanner(System.in); int n = reader.nextInt(); int width = (int)Math.log10(n * n) + 2; int [][] s = new int[n][n]; snake(n, 0, 0, 1, s); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) System.out.printf("%" + width + "d", s[i][j]); System.out.println(); } } }