Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]
.
一刷
題解:
轉圈打印矩陣肤寝,需要設置left, right, top和bot四個變量來控制分衫, 注意每次增加行/列前要判斷l(xiāng)ist所含元素是否小于矩陣的總元素數(shù)目德召。用邊界來控制堂飞,if條件中需要加入4個邊界。
Time Complexity - O(mn), Space Complexity - O(1)
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if(matrix == null || matrix.length == 0) return res;
int n = matrix.length, m = matrix[0].length;
int top = 0, bottom = n-1, left = 0, right = m-1;
int total = n*m;
while(total>0){
for(int i=left; i<=right; i++){
res.add(matrix[top][i]);
total--;
}
top++;
if(total>0){
for(int i=top; i<=bottom; i++){
res.add(matrix[i][right]);
total--;
}
right--;
}
if(total>0){
for(int i=right; i>=left; i--){
res.add(matrix[bottom][i]);
total--;
}
bottom--;
}
if(total>0){
for(int i=bottom; i>=top; i--){
res.add(matrix[i][left]);
total--;
}
left++;
}
}
return res;
}
}