蛇形举证样例:
维数为3:
1 2 3
8 9 4
7 6 5
维数为5:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
13 12 11 10 9
代码输入输出实例:
输入:3
输出: 1 2 3 8 9 4 7 6 5
/** * 蛇形矩阵 * @author dell1 * */ public class martix { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] data = create(n); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length; j++) { System.out.print(data[i][j] + " "); } } } public static int[][] create(int n){ int[][] data = new int[n][n]; int size = n; int num = 1; for (int i = 0; i < data.length-1; i++) { int j = i; int k = i; for (; k < size; k++) { data[j][k] = num++; } if (data.length-2*i>0) { j++; for (k--; j < size; j++) { data[j][k] = num++; } k--; for (j--; k > i; k--) { data[j][k] = num++; } for (; j > i; j--) { data[j][k] = num++; } size--; } } return data; } }