Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Time Complexity
O(mn)
思路
We should think about these test cases :
if matrix == null, matrix.length == 0, matrix[0] == null, matrix[0].length == 0
if matrix just has one row
1 2 3
if matrix just has one column
1
2
3
if matrix is even
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
we're going to print it in this order
1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10
if matrix is odd
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
print it in this order
1 2 3 4 5 6
12 18
17 16 15 14 13
7
if(rowStart > rowEnd || colStart > colEnd) break; it means it just have one row or one col left, so when it finish go right and go down. It should not do go left and go down anymore.
代码
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
//corner case
if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res;
int rows = matrix.length, cols = matrix[0].length;
int rowStart = 0, colStart = 0, rowEnd = rows - 1, colEnd = cols - 1;
while(rowStart <= rowEnd && colStart <= colEnd){
//go right
for(int i = colStart; i <= colEnd; i++){
res.add(matrix[rowStart][i]);
}
rowStart++;
//go down
for(int i = rowStart; i <= rowEnd; i++){
res.add(matrix[i][colEnd]);
}
colEnd--;
if(rowStart > rowEnd || colStart > colEnd) break;
//go left
for(int i = colEnd; i >= colStart; i--){
res.add(matrix[rowEnd][i]);
}
rowEnd--;
//go up
for(int i = rowEnd; i >= rowStart; i--){
res.add(matrix[i][colStart]);
}
colStart++;
}
return res;
}
本文介绍了一种螺旋矩阵遍历算法,该算法可以按螺旋顺序返回矩阵中的所有元素。适用于不同大小和形状的矩阵,包括特殊情况如单行或单列矩阵。通过四个基本步骤:向右、向下、向左、向上进行遍历,并避免重复访问。
220

被折叠的 条评论
为什么被折叠?



