/** * @param {number} n * @return {number[][]} */ var generateMatrix = function (n) { let res = Array(n).fill(0).map(() =>Array(n).fill(0)); let rowBegin = 0; let rowEnd = n - 1; let colBegin = 0; let colEnd = n - 1; let num = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) { // right for (let i = colBegin; i <= colEnd; i++) { res[rowBegin][i] = num++; } rowBegin++;
// down for (let i = rowBegin; i <= rowEnd; i++) { res[i][colEnd] = num++; } colEnd--;
// left for (let i = colEnd; i >= colBegin; i--) { res[rowEnd][i] = num++; } rowEnd--;
// up for (let i = rowEnd; i >= rowBegin; i--) { res[i][colBegin] = num++; } colBegin++; } return res; };