方法一
- 将循环一圈定义为填充一次上、右、下、左。
- 在循环填充过程中,要定义填充的起点和终点的边界,本解法采用左闭右开的边界。
- 左闭右开解释:填充上侧时,包含左边界,而不包含右边接;填充右侧时,包含上边界,而不包含下边界;填充下侧时,包含右边界,而不包含左边界;填充左侧时,包含下边界,而不包含上边界。
- 上图每一种颜色代表各自遍历时的长度。
class Solution {
public int[][] generateMatrix(int n){
int[][] arr = new int[n][n];
int loop = n / 2;
int startX = 0;
int startY = 0;
int offset = 1;
int value = 1;
while (loop > 0) {
int i = startX;
int j = startY;
for (; j < startY + n - offset; ++j) {
arr[i][j] = value++;
}
for (; i < startX + n - offset; ++i) {
arr[i][j] = value++;
}
for (; j > startY; j--) {
arr[i][j] = value++;
}
for (; i > startX; i--) {
arr[i][j] = value++;
}
startX++;
startY++;
offset += 2;
loop--;
}
if (n % 2 == 1) {
int mid = n / 2;
arr[mid][mid] = value;
}
return arr;
}
}
方法2
- 使用遍历来定义左、右、上、下的边界;
- 同理,采用左闭右开的规则控制边界。
class Solution {
public int[][] generateMatrix(int n){
int[][] arr = new int[n][n];
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
int endNum = n * n;
int value = 1;
while (value < endNum) {
int row;
int culumn;
for (culumn = left; culumn < right; culumn++) {
arr[top][culumn] = value++;
}
for (row = top; row < bottom; row++) {
arr[row][right] = value++;
}
for (culumn = right; culumn > left; culumn--) {
arr[bottom][culumn] = value++;
}
for (row = bottom; row > top; row--) {
arr[row][left] = value++;
}
top++;
right--;
bottom--;
left++;
}
if (n % 2 == 1) {
arr[n / 2][n / 2] = value;
}
return arr;
}
}
参考:代码随想录
|