-
题目
输入两个整数n和m,输出一个n行m列的矩阵,将数字 1 到 n*m 按照回字蛇形填充至矩阵中。
具体矩阵形式可参考样例。
-
输入格式
输入共一行,包含两个整数n和m。
-
输出格式
输出满足要求的矩阵。
矩阵占n行,每行包含m个空格隔开的整数。
-
数据范围
1≤n,m≤100
-
输入样例
3 3
-
输出样例
1 2 3 8 9 4 7 6 5
-
代码1
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int m = sc.nextInt(); int n = sc.nextInt(); int[][] res = new int[m][n]; int left = 0, right = n - 1, top = 0, bottom = m - 1; int num = 1; while(num <= m * n) { for(int i = left; i <= right && num <= m * n; i++) { res[top][i] = num++; } top++; for(int i = top; i <= bottom && num <= m * n; i++) { res[i][right] = num++; } right--; for(int i = right; i >= left && num <= m * n; i--) { res[bottom][i] = num++; } bottom--; for(int i = bottom; i >= top && num <= m * n; i--) { res[i][left] = num++; } left++; } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { System.out.print(res[i][j] + " "); } System.out.println(); } } }
-
代码2
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int row = sc.nextInt(); int col = sc.nextInt(); int res[][] = new int[row][col]; int[] dx = new int[]{-1, 0, 1, 0}; int[] dy = new int[]{0, 1, 0, -1}; int x = 0, y = 0, d = 1; for(int num =1; num <= row * col; num++) { res[x][y] = num; int next_x = x + dx[d]; int next_y = y + dy[d]; if(next_x < 0 || next_x >= row || next_y < 0 || next_y >= col || res[next_x][next_y] != 0) { d = (d + 1) % 4; next_x = x + dx[d]; next_y = y + dy[d]; } x = next_x; y = next_y; } for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { System.out.print(res[i][j] + " "); } System.out.println(); } } }
01-02
440
01-29
1132
06-01
115
12-05
147