54-螺旋矩阵
题目描述
给你一个 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]
分析
先初始化n*n的数组,所有的值都为0
然后遍历从1到n*n,定义一个前进方向,右下左上依次切换,切换的条件是如果按照当前方向前进的话,下一个值为undefined或者不为0(已在exists数组里面)的时候,则换成下一个方向。
题解
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
let res = [];
let exists = [];
let m = matrix.length;
let n = matrix[0].length;
let x=y=0;
let index = 0; // 当前方向
let chioces = [
[1, 0], // 向右
[0, 1], // 向下
[-1, 0], // 向左
[0, -1], // 向上
]
for(let cnt=1; cnt<m*n+1; cnt++) {
exists.push(y*n+x);
res.push(matrix[y][x])
let newy = y+chioces[index][1]
let newx = x+chioces[index][0]
if(matrix[newy]==undefined || matrix[newy][newx]==undefined || exists.includes(newy*n+newx)) {
index = (index + 1) % 4
}
y = y+chioces[index][1]
x = x+chioces[index][0]
}
return res
};
分析
时间复杂度:O(m*n)
空间复杂度:O(m*n)
优化 - 按层模拟
不断更新边界,可以将空间复杂度降低至 O(1)
难点
模拟、螺旋打印