顺时针回型遍历
- left, right, top, bottom
- 上侧: 访问 arr[top][left:right]
- 右侧: 访问 arr[top+1:bottom][right]
- 下侧: 访问 arr[bottom][right-1:left]
- 左侧: 访问 arr[bottom-1, top+1][left]
- 接着访问里面一层, left-1 , right+1 , top+1 , bottom-1
import java.util.Scanner;-
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int count = 0;
int[][] arr = new int[n][m];
int top = 0, bottom = n-1;
int left = 0, right = m-1;
//顺时针逐层遍历
while (left <= right && top <= bottom){
for (int k = left; k <= right ; k++) {
arr[top][k] = ++count;
}
for (int k = top + 1; k <= bottom ; k++) {
arr[k][right] = ++count;
}
if(top < bottom) {
for (int k = right - 1; k >= left; k--) {
arr[bottom][k] = ++count;
}
}
if(left < right) {
for (int k = bottom - 1; k >= top + 1; k--) {
arr[k][left] = ++count;
}
}
left++;
right--;
top++;
bottom--;
}
//输出
for (int i = 0; i < n ; i++) {
for (int j = 0; j < m; j++) {
if(j > 0){
System.out.print(" ");
}
System.out.print(arr[i][j]);
}
System.out.println();
}
}
}