๋ฐ์ํ
๐ค๋ฌธ์ ํด๊ฒฐ
- ํ ๋ฐฉ์์ ๋ชจ๋ P์ ๋ํ์ฌ ์ฐจ๋ก๋ก ์ฃผ๋ณ์ ํ์ํ๋ค. ์ฝ๊ฐ BFS ๋๋๐ค
- O๋ฅผ ๋ง๋๋ฉด ๊ณ์ํ์
- P๋ฅผ ๋ง๋๋ฉด ๋ฉ์ถ๋ค. - ๊ฑฐ๋ฆฌ๋๊ธฐ ์ง์ผ์ง์ง ์์
- ํ์ ์ค P์ ๋ํ์ฌ ๊ฑฐ๋ฆฌ๊ฐ 2๊ฐ ๋๋ฉด ๋ ์ด์ ๊ทธ ์ง์ ์์๋ ํ์์ ๋ฉ์ถ๋ค.
- ๊ทธ๋ฌ๋ฏ๋ก ํ์ ์ค ๋ค๋ฅธ P๋ฅผ ๋ง๋ฌ๋ค๋ ๋ง์ ๊ฑฐ๋ฆฌ๊ฐ 2 ์ดํ์ด๊ธฐ ๋๋ฌธ์ ํ๋ฝ
- X๋ ๋ฌด์
๐จ ํ์ด์ฌ์ผ๋ก ํ๋ ๋๋์ผ๋ก ํ์๋ค. break๋ฅผ ํ๋ฒ์ ๊ฑธ์ด์ฃผ๋ ๋ฐฉ๋ฒ์ด ์๋...
๐ป์์ค ์ฝ๋
function solution(places) {
var answer = [];
var length = places[0].length;
var dx = [-1, 1, 0, 0] // ์ ํ ์ข ์ฐ
var dy = [0, 0, -1, 1]
for (var place of places) {
var isRight = false;
for (var i = 0; i < length; i++) {
for (var j = 0; j < length; j++) {
if (place[i][j] === 'P') {
// ํฌ๊ธฐ๊ฐ ๊ฐ์ ๋น์ด์๋ 2์ฐจ์ ๋ฐฐ์ด
var placeDistance = Array.from(Array(length), () => new Array(length).fill(-1));
var stack = [[i, j]];
placeDistance[i][j] = 0;
while (stack.length > 0 && isRight === false) {
[cx, cy] = stack.pop();
if (placeDistance[cx][cy] == 2) continue; // ๊ฑฐ๋ฆฌ๊ฐ 2๋งํผ์ ๋น ๊ณต๊ฐ์ด๋ฏ๋ก ์ฒดํฌํ ํ์ ์์
for (let k = 0; k < dx.length; k++) {
var nx = cx + dx[k];
var ny = cy + dy[k];
if (nx >= 0 && nx < length && ny >= 0 && ny < length && placeDistance[nx][ny] == -1) {
if (place[nx][ny] === 'O') { // ๋น ๊ณต๊ฐ์ด๋ฉด ๊ฑฐ๋ฆฌ 1 ๋ฃ๊ณ
placeDistance[nx][ny] = placeDistance[cx][cy] + 1;
stack.push([nx, ny]);
} else if (place[nx][ny] === 'P') { // P๋ฅผ ๋ง๋๋ฉด ๊ฑฐ๋ฆฌ 2 ์ด๋ด์ ๋ง๋ฌ์ผ๋ฏ๋ก ๊ฑฐ๋ฆฌ๋๊ธฐ ์ง์ผ์ง์ง ์์
stack = [];
isRight = true;
break
}
}
}
}
if(isRight) break;
}
if(isRight) break;
}
}
if (isRight) {
answer.push(0);
} else {
answer.push(1);
}
}
return answer;
}
console.log(solution([["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]]));
๐๋ฌธ์ ํ์ธ
์ถ์ฒ: ํ๋ก๊ทธ๋๋จธ์ค
๋ฐ์ํ