Open wordlex opened 3 years ago
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
const rows = matrix.length // 总的行数
const columns = matrix[0].length // 总的列数
let left = 0
let right = columns - 1
let top = 0
let bottom = rows - 1
const result = new Array()
while(left <= right && top <= bottom) {
// 从左往右
for (let col = left; col <= right; col++) {
result.push(matrix[top][col])
}
// 从上往下
for(let row=top+1; row <= bottom; row++) {
result.push(matrix[row][right])
}
if (left < right && top < bottom) {
// 从右往左
for(let col=right-1; col>left; col--) {
result.push(matrix[bottom][col])
}
// 从下往上
for(let row=bottom; row>top; row--) {
result.push(matrix[row][left])
}
}
left++
right--
top++
bottom--
}
return result
};
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
let top = 0,
right = matrix[0].length - 1,
bottom = matrix.length - 1,
left = 0;
// 总数
let amount = matrix[0].length * matrix.length
let result = [];
while (amount > 0) {
// 横
for (let i = left; i <= right && amount > 0; i++) {
result.push(matrix[top][i])
amount--
}
// 缩小边界
top++
// 竖
for (let i = top; i <= bottom && amount > 0; i++) {
result.push(matrix[i][right])
amount--
}
right--
for (let i = right; i >= left && amount > 0; i--) {
result.push(matrix[bottom][i])
amount--
}
bottom--
for (let i = bottom; i >= top && amount > 0; i--) {
result.push(matrix[i][left])
amount--
}
left++
}
return result;
};
https://leetcode-cn.com/problems/spiral-matrix/