需要处理好边界值即可,在四个方向上逐步缩减迭代的范围,同时进行计数
跳出循环的条件是 < ,不能是 <=,因为在相等的时候已经迭代完了,就跳不出循环,导致超时
第一种解法
var spiralOrder = function (matrix) {
let row = matrix.length, col = matrix[0].length
let up = 0, left = 0, bottom = row - 1, right = col - 1
let cnt = 0, res = []
while (cnt < row * col) {
// up
if (up <= bottom) {
for (let i = left; i <= right; ++i) {
res.push(matrix[up][i])
cnt++
}
up++
}
// right
if (left <= right) {
for (let i = up; i <= bottom; ++i) {
res.push(matrix[i][right])
cnt++
}
right--
}
// bottom
if (up <= bottom) {
for (let i = right; i >= left; --i) {
res.push(matrix[bottom][i])
cnt++
}
bottom--
}
// left
if (left <= right) {
for (let i = bottom; i >= up; --i) {
res.push(matrix[i][left])
cnt++
}
left++
}
}
return res
};
第二种解法
上面利用了计数器来跳出循环,其实这里可以不用计数器这个中间变量
直接判断 up bottom left right 这些边界条件即可,在满足 up <= bottom && left <= right 的情况下就需要继续进行遍历
需要注意的是,在bottom以及left进行遍历的时候,需要判断边界条件,以防越界
举例,在up进行遍历的时候up++,可能此时up已经大于bottom了,若此时继续进行底部的遍历,那么就会导致重复了
var spiralOrder = function (matrix) {
let rows = matrix.length, cols = matrix[0].length
let up = 0, bottom = rows - 1, left = 0, right = cols - 1
let res = []
while (up <= bottom && left <= right) {
// up
for (let i = left; i <= right; ++i) {
res.push(matrix[up][i])
}
up++
// right
for (let i = up; i <= bottom; ++i) {
res.push(matrix[i][right])
}
right--
// bottom
if (up <= bottom) {
for (let i = right; i >= left; --i) {
res.push(matrix[bottom][i])
}
bottom--
}
// left
if (left <= right) {
for (let i = bottom; i >= up; --i) {
res.push(matrix[i][left])
}
left++
}
}
return res
};