
for문을 돌며 격자판을 초기화 했는데 Array.from()으로 간단히 만드는 방법이 있어서 공유합니다.
// 내가 만든 격자판 초기화
let answer = [];
for (let i = 0; i < n; i++) {
let row = [];
for (let j = 0; j < n; j++) {
row.push(0);
}
answer.push(row);
}
// 간단한 격자판 초기화
// Array(5).fill(0) === [ 0, 0, 0, 0, 0 ]
let answer = Array.from({ length: n }, () => Array(n).fill(0));

위 그림처럼 2 * (i + 1) 번을 4번씩 도는 규칙으로 구현했습니다.
var fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\n");
const [n, target] = input.map(Number);
function solution(n, target) {
// 격자판 초기화
let answer = Array.from({ length: n }, () => Array(n).fill(0));
const mid = Math.floor(n / 2);
answer[mid][mid] = 1;
let cnt = 1;
let [x, y] = [mid, mid];
// target 좌표 변수
let [tx, ty] = [0, 0];
for (let i = 0; i < mid; i++) {
for (let j = 0; j < 4; j++) {
// 위 밑 왼 위
if (j === 0) x += -1;
if (j === 1) x += 1;
if (j === 2) y += -1;
if (j === 3) x += -1;
answer[x][y] = ++cnt;
// cnt이 target일때
if (cnt === target) {
[tx, ty] = [x + 1, y + 1];
}
for (let s = 1; s < 2 * (i + 1); s++) {
// 2 * i 만큼 오 밑 왼 오
if (j === 0) y += 1;
if (j === 1) x += 1;
if (j === 2) y += -1;
if (j === 3) x += -1;
answer[x][y] = ++cnt;
if (cnt === target) {
[tx, ty] = [x + 1, y + 1];
}
}
}
}
answer.push([tx, ty]);
answer = answer.map((v) => v.join(" ")).join("\n");
console.log(answer);
}
solution(n, target);