题目
解题
解题一:模拟
// javascript
var spiralOrder = function(matrix) {
if (!matrix.length || !matrix[0].length) return [];
const rows = matrix.length, columns = matrix[0].length;
const visited = new Array(rows).fill(0).map(() => new Array(columns).fill(false));
const totalCnt = rows * columns;
const order = new Array(totalCnt);
let dirIdx = 0, row = 0, col = 0;
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
for (let i = 0; i < totalCnt; i++) {
order[i] = matrix[row][col];
visited[row][col] = true;
const nextRow = row + directions[dirIdx][0], nextCol = col + directions[dirIdx][1];
if (nextRow < 0 || nextRow >= rows || nextCol < 0 || nextCol >= columns || visited[nextRow][nextCol]) {
dirIdx = (dirIdx + 1) % 4;
}
row += directions[dirIdx][0];
col += directions[dirIdx][1];
}
return order;
};
解题二:按层模拟
如果 left === right || top === bottom
,说明当前 while 循环遍历的元素全部在一列或者一行上。
// javascript
var spiralOrder = function(matrix) {
if (!matrix.length || !matrix[0].length) return [];
const rows = matrix.length, columns = matrix[0].length;
const order = new Array(rows * columns);
let index = 0;
let left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) { // 有等于
for (let col = left; col <= right; col++) {
order[index++] = matrix[top][col];
}
for (let row = top + 1; row <= bottom; row++) {
order[index++] = matrix[row][right];
}
if (left < right && top < bottom) { // 没有等于
for (let col = right - 1; col > left; col--) {
order[index++] = matrix[bottom][col];
}
for (let row = bottom; row > top; row--) {
order[index++] = matrix[row][left];
}
}
[left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1];
}
return order;
};