개발자 톡
JS 풀이
- 등록일
- 2025-02-06 16:09:56
- 조회수
- 44
- 작성자
- saungin1228
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const input = []
const move = [[1,0] , [0 , 1] , [-1,0] , [0 ,-1]]
let board
const checkLocation = (y , x) => 0 <=y && y <board.length && 0 <=x && x <board[0].length;
function isGhost(ghostBoard , y , x , day){
return ghostBoard[y][x] <= day
}
function makeGhostBoard(Ghost , low, col){
const board = new Array(low).fill(0).map(_ => new Array(col).fill(Infinity))
const queue = []
for (const [y , x] of Ghost){
queue.push([y ,x , 0])
board[y][x] = 0
}
let index = 0;
while(index < queue.length){
const [curY , curX , curCount] = queue[index++]
for(let dir = 0; dir < 4; dir++){
const [yy ,xx] = move[dir];
const [nextY , nextX] = [curY + yy , curX + xx]
if (!checkLocation(nextY, nextX))
continue;
if (board[nextY][nextX] <= curCount+1){
continue
}
board[nextY][nextX] = curCount+1
queue.push([nextY , nextX , curCount+1])
}
}
return board
}
rl.on("line" , (line) => {
input.push(line.trim())
}).on("close" , () => {
const [low , col] = input.shift().split(" ").map(v => +v)
board = input.map(v => v.split(""))
const Ghost = []
let Exit
let Start
// visited
for (let i=0; i< board.length; i++){
for (let j=0; j< board[0].length; j++){
const cur = board[i][j]
if (cur === "G"){
Ghost.push([i , j])
continue;
}
if (cur === "D"){
Exit = [i, j]
continue;
}
if (cur ==="N"){
Start = [i, j]
continue;
}
}
}
const ghostBoard = makeGhostBoard(Ghost , low, col)
const queue = [[Start[0] , Start[1] , 1]]
let index = 0;
while (index < queue.length){
const [curY , curX , curDay] = queue[index++]
// console.log(curY , curX , curDay)
// 종료 조건
if (curY === Exit[0] && curX === Exit[1]){
console.log("Yes")
return;
}
// 다음 조건
for(let dir = 0; dir < 4; dir++){
const [yy ,xx] = move[dir];
const [nextY , nextX] = [curY + yy , curX + xx]
if (!checkLocation(nextY, nextX))
continue;
if (board[nextY][nextX] === "N")
continue;
if (board[nextY][nextX] === "#")
continue
if (board[nextY][nextX] === "G")
continue;
if (isGhost(ghostBoard , nextY , nextX , curDay))
continue
board[nextY][nextX] = "N"
queue.push([nextY , nextX , curDay+1])
}
}
console.log("No")
})