var generateMatrix = function (n) { let arr = []; for (let i = 0; i < n; i++) { arr.push(Array(n).fill(0)); } let count = n * n; let num = 1; let i = 0; let j = 0; let dir = "right"; while (num <= count) {
if (dir == "right") { arr[i][j] = num; j++; if (j >= n || arr[i][j] != 0) { dir = "down"; j = j - 1; i++; } } elseif (dir == "down") { arr[i][j] = num; i++; if (i >= n || arr[i][j] != 0) { i = i - 1; dir = "left"; j--; } } elseif (dir == "left") { arr[i][j] = num; j--; if (j < 0 || arr[i][j] != 0) { j = j + 1; dir = "top"; i--; } } elseif (dir == "top") {
arr[i][j] = num; i--;
if (i < 0 || arr[i][j] != 0) { i = i + 1; dir = "right"; j++; } } num++; } return arr;