dhl9810   2년 전

풀이는 문제가 없는 거 같은데 자꾸 시간초과가 발생하네요 ㅜ 

혹시 이유를 알려주실분 있으실까요?

감사합니다

kny030303   2년 전

const map = input.map((line) => {

return line.split("").map((n) => parseInt(n));

});

string을 number로 바꿔주는 부분에서 시간초과가 나는것 같습니다.
dist배열을 따로 만드셔서 거리를 구하시던지 string을 더하셔야합니다.
아래는 작성자 분 코드에서 parseInt(n) 부분을 제외하고 작성한 코드입니다. 

const fs = require("fs");const path = require("path");const dir = path.join(__dirname, "/test.txt");
const filePath = process.platform === "linux" ? "/dev/stdin" : dir;const input = fs.readFileSync(filePath).toString().trim().split("\n");
function solution(input) { const [N, M] = input .shift() .split(" ") .map((n) => Number(n));
const map = input.map((line) => line.split("")); const visited = Array.from({ length: N }, () => Array(M).fill(0));
const direction = [ [-1, 0], [1, 0], [0, 1], [0, -1], ];
function BFS(graph, start, visited) { const [n, m] = start; const queue = [];
visited[n][m] = 1; queue.push(start);
while (queue.length) { const [n, m] = queue.shift(); if (N === n && M === m) { break; }
for (let i = 0; i < direction.length; i++) { const [dx, dy] = direction[i]; const nextX = m + dx; const nextY = n + dy;
if (nextX < 0 || nextX >= M || nextY < 0 || nextY >= N) { continue; }
if (graph[nextY][nextX] === "1" && !visited[nextY][nextX]) { queue.push([nextY, nextX]); visited[n][m] = 1; graph[nextY][nextX] = graph[n][m] + 1; } } } }
BFS(map, [0, 0], visited);
return map[N - 1][M - 1];}
console.log(solution(input).length);

댓글을 작성하려면 로그인해야 합니다.