leetcode 59题 螺旋矩阵2
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
leetcode 54题 螺旋矩阵1
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
太长不看总结:如果最小的边是奇数的话,那么就需要单独处理中间位置剩下的特殊行/特殊列,如果rows > columns,则是中间列,相反,则是中间行
59题是正方形,54题是长方形,需要考虑长方形长和宽两个边界条件
模拟顺时针画矩阵的过程:
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
loop的计算: 本题的loop计算与59.螺旋矩阵II算法略微差异,因为存在rows和columns两个维度,可自行分析,loop只能取min(rows, columns),例如rows = 5, columns = 7,那loop = 5 / 2 = 2
mid的计算及填充: 1、同样的原理,本题的mid计算也存在上述差异; 2、 如果min(rows, columns)为偶数,则不需要在最后单独考虑矩阵最中间位置的赋值 如果min(rows, columns)为奇数,则矩阵最中间位置不只是, 而是会留下来一个特殊的中间行或者中间列,具体是中间行还是中间列,要看rows和columns的大小,如果rows > columns,则是中间列,相反,则是中间行
public List<Integer> spiralOrder(int[][] matrix) {
int m = matrix.length; // row
int n = matrix[0].length; // column
int minLength = Math.min(m, n);
List<Integer> res = new ArrayList<>();
int count = 0;
for(int offset = 0; offset < minLength/2; offset++) {
// 填充上行从左到右
for(int i = offset; i < n - offset - 1; i++) {
res.add(matrix[offset][i]);
}
// 填充右列从上到下
for(int i = offset; i < m - offset - 1; i++) {
res.add(matrix[i][n - 1 - offset]);
}
// 填充下行从右到左
for(int i = n - offset - 1; i > offset; i--) {
res.add(matrix[m - offset - 1][i]);
}
// 填充左列从下到上
for(int i = m - offset - 1; i > offset; i--) {
res.add(matrix[i][offset]);
}
}
// 处理中间的部分
if (minLength % 2 == 1) {
if (m == minLength) {
for(int i = minLength / 2; i < n - minLength / 2; i++) {
res.add(matrix[minLength / 2][i]);
}
} else if (n == minLength) {
for(int i = minLength / 2; i < m - minLength / 2; i++) {
res.add(matrix[i][minLength / 2]);
}
}
}
return res;
}
而59题呢因为是正方形,是54题的一种特殊实现方式,所以只需要考虑中间的元素
if(n%2 == 1) {
res[n/2][n/2] = count;
}