题解 | 螺旋矩阵(二)
螺旋矩阵(二)
https://www.nowcoder.com/practice/2c8078a728834e81a046fdefdea049aa
import java.util.*;
public class Solution {
/**
*
*/
public int[][] Matrix (int n) {
int[][] matrix = new int[n][n];
// 初始化四面墙的边界
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
int num = 1;
while (true) {
//往右
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
// 顶墙下移,如果超过底墙则结束(这一行遍历完了,没有用了,top++)
if (++top > bottom) break;
//往下
for (int i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
// 右墙左移,如果超过左墙则结束(这一列遍历完了,没有用了,right--)
if (--right < left) break;
//往左
for (int i = right; i >= left; i--) {
matrix[bottom][i] = num++;
}
// 底墙上移,如果超过顶墙则结束(这一行遍历完了,没有用了,bottom--)
if (--bottom < top) break;
//往上
for (int i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
// 左墙右移,如果超过右墙则结束(这一列遍历完了,没有用了,left++)
if (++left > right) break;
}
return matrix;
}
}

查看29道真题和解析