์ฐ์ ์๊ฐ์ด๊ณผ๋ก ์ฐพ์์ค์ ๋ถ!!!
queue๋ฅผ ์ง์ ๊ตฌํํ์ง ์๊ณ ๋ฐฐ์ด ๋ฉ์๋ shift ์ฐ์๋ฉด ์๊ฐ ์ด๊ณผ๋ฉ๋๋ค ใ
ใ
๐ก์ ๊ทผ๋ฐฉ๋ฒ
- ์ต์ ์ผ์๋ฅผ ๊ตฌํ๋ ๊ฒ
- ์ธ์ ํ ๋งํ ๋ค์ด ๋จผ์ ์ต๋ ๊ฒ
-> BFS๋ค!!
1. ์ฐฝ๊ณ ์์ ์ต์ด ์๋ ํ ๋งํ ๋ค์ ์ฐพ์์ ํ์ ๋ฃ๊ณ
2. ์ต์ด ์๋ ํ ๋งํ ์ ์ธ์ ํ ๋งํ ๋ค์ด ์ต๋๋ก BFS๋ก ํ์
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
enqueue(val) {
var newNode = new Node(val);
if (!this.first) {
this.first = newNode;
this.last = newNode;
} else {
this.last.next = newNode;
this.last = newNode;
}
return ++this.size;
}
dequeue() {
if (!this.first) return null;
var temp = this.first;
if (this.first === this.last) {
this.last = null;
}
this.first = this.first.next;
this.size--;
return temp.value;
}
}
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
// ์
๋ ฅ๊ฐ์ด ์ฒซ ๋ฒ์งธ ์ค์๋ ์
๋ ฅ ๊ฐ์ ๊ธธ์ด(n), n๊ฐ์ ์ค์ ๊ฑธ์ณ์ ํ ์ค์ ํ๋์ ์
๋ ฅ๊ฐ์ด ์ฃผ์ด์ง ๋
const [n, ...input] = require('fs')
.readFileSync(filePath)
.toString()
.trim()
.split('\n');
function solution(n, m, box) {
const queue = new Queue();
let min = 0;
const dx = [0, 0, 1, -1];
const dy = [1, -1, 0, 0];
//์ ์ต์ ํ ๋งํ ๊ฐ์
let allCnt = 0;
//๋ฐ์ค๋ฅผ ๋๋ฉด์ ์ต์ ํ ๋งํ ๋ค ์์น ๊ตฌํ๊ธฐ
//์ ์ต์ ํ ๋งํ ๊ฐ์๋ ์ฒดํฌ
box.forEach((row, rIdx) => {
row.forEach((col, cIdx) => {
if (col === 1) {
queue.enqueue([rIdx, cIdx, 0]);
} else if (col === 0) {
allCnt++;
}
});
});
//์ต์ ํ ๋งํ ๊ฐ ์์ผ๋ฉด return -1
if (queue.size === 0) return -1;
while (queue.size) {
//r=row idx, c= column idx, cnt=์ง๊ธ ํ ๋งํ ๊ฐ ์ต๋๋ฐ ๊ฑธ๋ฆฌ๋ ๋ ์ง
const [r, c, cnt] = queue.dequeue();
min = Math.max(cnt, min);
for (let i = 0; i < 4; i++) {
if (
r + dy[i] >= 0 &&
r + dy[i] < m &&
c + dx[i] >= 0 &&
c + dx[i] < n &&
box[r + dy[i]][c + dx[i]] === 0
) {
//์ ์ต์ ํ ๋งํ ๊ฐ์ --;
//์ ์ต์ ํ ๋งํ ๋ ํ์ ๋ฃ๊ณ 1++;
allCnt--;
box[r + dy[i]][c + dx[i]] = 1;
queue.enqueue([r + dy[i], c + dx[i], cnt + 1]);
}
}
}
//์ ์ต์ ํ ๋งํ ๊ฐ ์์ ๊ฒฝ์ฐ,
return allCnt === 0 ? min : -1;
}
const nArr = n.split(' ').map(Number);
const answer = solution(
nArr[0],
nArr[1],
input.map((row) => row.split(' ').map(Number)),
);
console.log(answer);
'๐ง ์๊ณ ๋ฆฌ์ฆ > ์ ํ๋ณ ๋ํ๋ฌธ์ ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ค์ต์คํธ๋ผ][๋ฐฑ์ค] 117799 ์ต์๋น์ฉ ๊ตฌํ๊ธฐ2 JS (2) | 2024.01.10 |
---|---|
[์์์ ๋ ฌ][๋ฐฑ์ค] 2252 JS ํ์ด (1) | 2023.12.28 |
[MST][๋ฐฑ์ค] 1197 ์ต์ ์คํจ๋ ํธ๋ฆฌ JS ํ์ด (1) | 2023.12.28 |
MST ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ ์ค๋ช (0) | 2023.12.28 |