Skip to content

Commit

Permalink
refactor : bfs(미로 탐색)
Browse files Browse the repository at this point in the history
  • Loading branch information
luckylooky2 committed Oct 5, 2023
1 parent 5002c31 commit 1eaf918
Showing 1 changed file with 24 additions and 32 deletions.
56 changes: 24 additions & 32 deletions baekjoon/2178.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,50 +10,42 @@ const [n, m] = input
.split(" ")
.map((v) => parseInt(v, 10));
const map = input.map((v) => v.split("").map((v) => parseInt(v, 10)));
const visited = map.map((v) => v.map((v) => false));
const visited = map.map((v) => v.map((v) => 0));
const dir = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1],
];
const q1 = new Queue();
const q2 = new Queue();
let isFirst = true;
const q = new Queue();
let i = 0,
j = 0;
let cnt = 1;
let flag = false;

q1.push([i, j]);
visited[i][j] = true;
q.push([i, j]);
visited[i][j] = 1;

while (!(q1.size === 0 && q2.size === 0)) {
while (isFirst ? q1.size !== 0 : q2.size !== 0) {
const top = isFirst ? q1.head.value : q2.head.value;
isFirst ? q1.pop() : q2.pop();
for (let i = 0; i < 4; i++) {
const next = [top[0] + dir[i][0], top[1] + dir[i][1]];
if (
next[0] < 0 ||
next[0] >= n ||
next[1] < 0 ||
next[1] >= m ||
map[next[0]][next[1]] === 0 ||
visited[next[0]][next[1]] === true
)
continue;
isFirst ? q2.push(next) : q1.push(next);
visited[next[0]][next[1]] = true;
if (next[0] === n - 1 && next[1] === m - 1) {
flag = true;
break;
}
while (q.size !== 0) {
const top = q.head.value;
q.pop();
for (let i = 0; i < 4; i++) {
const next = [top[0] + dir[i][0], top[1] + dir[i][1]];
if (
next[0] < 0 ||
next[0] >= n ||
next[1] < 0 ||
next[1] >= m ||
map[next[0]][next[1]] === 0 ||
visited[next[0]][next[1]] > 0
)
continue;
q.push(next);
visited[next[0]][next[1]] = visited[top[0]][top[1]] + 1;
if (next[0] === n - 1 && next[1] === m - 1) {
flag = true;
break;
}
}
cnt++;
isFirst = !isFirst;
if (flag) break;
}

console.log(cnt);
console.log(visited[n - 1][m - 1]);

0 comments on commit 1eaf918

Please sign in to comment.