public void Solution(int m,int n){
int array[][]=new int[m][n];
int count=1;
int top=0,left=0;
int bottom=m-1,right=n-1;
while (left<=right&&top<= bottom){
//从左到右遍历上侧元素,依次为 (top,left) 到 (top,right)
for (int column =left; column <=right ; column++) {
array[top][column]=count++;
}
//从上到下遍历右侧元素,依次为 (top+1,right) 到 )(bottom,right)
for (int row=top+1;row<= bottom;row++){
array[row][right]=count++;
}
//如果 left<right 且 top<bottom,
if (left<right&&top<bottom){
//则从右到左遍历下侧元素(bottom,right−1) 到 (bottom,left+1)
for (int column=right-1;column>left;column--){
array[ bottom][column]=count++;
}
// 下到上遍历左侧元素,依次为(bottom,left)到(top+1,left)
for (int row= bottom;row>top;row--){
array[row][left]=count++;
}
}
//遍历完当前层的元素之后,将 eft 和 top 分别增加 1,将 right 和 }bottom 分别减少 1,
// 进入下一层继续遍历,直到遍历完所有元素为止
left++;
right--;
top++;
bottom--;
}
//遍历
for (int i = 0; i <array.length; i++) {
for (int j = 0; j <array[i].length; j++) {
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
运行结果如下所示: