目录结构
1.题目
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
模拟。
public class Solution54 {
@Test
public void test54() {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
System.out.println(spiralOrder(matrix));
}
public List<Integer> spiralOrder(int[][] matrix) {
int len1 = matrix.length, len2 = matrix[0].length;
int row1 = 0, row2 = len1 - 1, col1 = 0, col2 = len2 - 1, count = 0, num = len1 * len2;
List<Integer> result = new ArrayList<>();
while (count < num) {
for (int i = col1; i <= col2; i++) {
if (count++ == num) break;
result.add(matrix[row1][i]);
}
row1++;
for (int i = row1; i <= row2; i++) {
if (count++ == num) break;
result.add(matrix[i][col2]);
}
col2--;
for (int i = col2; i >= col1; i--) {
if (count++ == num) break;
result.add(matrix[row2][i]);
}
row2--;
for (int i = row2; i >= row1; i--) {
if (count++ == num) break;
result.add(matrix[i][col1]);
}
col1++;
}
return result;
}
}
- 时间复杂度:
- 空间复杂度: