Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upGitHub is where the world builds software
Millions of developers and companies build, ship, and maintain their software on GitHub — the largest and most advanced development platform in the world.
螺旋矩阵-54 #112
螺旋矩阵-54 #112
Comments
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
if(!matrix.length) return []
let n = matrix.length
let m = matrix[0].length
let total = n*m
let top = 0,bottom = n-1
let left = 0,right = m-1
let res = []
while(res.length < total){
for(let i=left;i<=right;i++) res.push(matrix[top][i]) // 从左到右
top++
for(let i=top;i<=bottom;i++) res.push(matrix[i][right]) // 从上到下
right--
/* 因为n 和 m 不相同的时候,最后可能会留一列或一行,避免重复计算,总数够了直接跳出去 */
if(res.length === total) break
for(let i=right;i>=left;i--) res.push(matrix[bottom][i]) // 从右到左
bottom--
for(let i=bottom;i>=top;i--) res.push(matrix[i][left]) // 从下到上
left++
}
return res
}; |

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
记录一个 visited 数组,从
0, 0开始,按照右 -> 下 -> 左 -> 上的方向不断前进,直到遇到边界或者已经访问过的元素 则切换成下一个方向,每访问一个元素就把结果放入
res数组中,最终当res的长度和矩阵大小一致时,就返回结果。这里方向用
dirs表示 4 个方向对应的偏移坐标,通过currentIndex指针不断递增来维护当前的方向,由于可能会超出方向数组的长度,所以每次取值都对 4 取余即可。