885. Spiral Matrix III
202408272247
tags: #array #matrix
var spiralMatrixIII = function(rows, cols, rStart, cStart) {
const DIRS = [[0, 1], [1, 0], [0, -1], [-1, 0]];
const res = [[rStart, cStart]];
let len = 0, direction = 0;
let r = rStart, c = cStart;
while (res.length < rows * cols) {
if (direction === 0 || direction === 2) {
len += 1;
}
for (let i = 0; i < len; i++) {
r += DIRS[direction][0];
c += DIRS[direction][1];
if (r >= 0 && r < rows && c >= 0 && c < cols) {
res.push([r, c]);
}
}
direction = (direction + 1) % 4;
}
return res;
};