LeetCode54 螺旋矩阵
题目
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
方法
模拟法
- 时间复杂度:O(mn),m为行数,n为列数
- 空间复杂度:O(mn)
class Solution {
public List spiralOrder(int[][] matrix) {
List ans = new ArrayList<>();
if(matrix==null||matrix.length==0||matrix[0].length==0){
return ans;
}
int rowLen = matrix.length , colLen = matrix[0].length;
int row = 0,col = 0,directionIndex = 0,total = rowLen*colLen;
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
boolean[][] visited = new boolean[rowLen][colLen];
for(int i=0;i=rowLen||nextCol<0||nextCol>=colLen||visited[nextRow][nextCol]){
directionIndex = (directionIndex+1)%4;
}
row += directions[directionIndex][0];
col += directions[directionIndex][1];
}
return ans;
}
}
优化版模拟法
先计算出边界:left,right,top,bottom,然后在边界内遍历
- 时间复杂度:O(mn),m为行数,n为列数
- 空间复杂度:O(1)
class Solution {
public List spiralOrder(int[][] matrix) {
List ans = new ArrayList<>();
if(matrix==null||matrix.length==0||matrix[0].length==0){
return ans;
}
int rows = matrix.length,cols = matrix[0].length;
int left = 0, right = cols-1, top = 0, bottom = rows-1;
while (left<=right&&top<=bottom){
for(int i = left;i<=right;i++){ //往右
ans.add(matrix[left][i]);
}
for(int i = top+1;i<=bottom;i++){ //往下
ans.add(matrix[i][right]);
}
if(leftleft;i--){ //往左
ans.add(matrix[bottom][i]);
}
for(int i = bottom;i>top;i--){ //往上
ans.add(matrix[i][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return ans;
}
}