๋ฌธ์ ๋งํฌ
ํ์ด ๋ฐฉ๋ฒ
์ ๋ต์ ๋ด๊ธฐ ์ํด ํ์ํ ๊ฐ๋ค์
- ๋ชจ๋ ์์ ๋ฉ์ด๋ฆฌ์ ํฌ๊ธฐ
- ์์ถ๊ด์ ๋ซ์ ์ ์๋ ์ด์์ ์ ๊ทผ ๊ฐ๋ฅํ ์์ ๋ฉ์ด๋ฆฌ์ ํฌ๊ธฐ์ ํฉ
- ๊ฐ ์ด์์ ์ ๊ทผ ๊ฐ๋ฅํ ์์ ๋ฉ์ด๋ฆฌ์ ํฌ๊ธฐ์ ํฉ์ ์ ์ฅํ๊ธฐ ์ํด land์ ์ด์ ํฌ๊ธฐ์ ๊ฐ์ 1์ฐจ์ ๋ฐฐ์ด(oilArr)์ ๋ง๋ญ๋๋ค.
- land์ ๋ชจ๋ ์์๋ฅผ ๋ฐฉ๋ฌธํ๋ฉด์ bfs๋ก ๋ชจ๋ ์์ ๋ฉ์ด๋ฆฌ์ ํฌ๊ธฐ๋ฅผ ๊ตฌํฉ๋๋ค.
- ํ ๋ฉ์ด๋ฆฌ๋ฅผ ๊ตฌํ ๋๋ง๋ค ๊ฐ col๋ณ๋ก ์์ ๋ฉ์ด๋ฆฌ์ ํฌ๊ธฐ๋ฅผ oilArr์ ๋ํด์ค๋๋ค.
bfs๋ฅผ ์ฌ์ฉํ ๋์๋ ์๊ฐ ์ ํ์ ๊ฑธ๋ฆด ๊ฒฝ์ฐ๋ฅผ ๋๋นํด์ ์ง์ ํ๋ฅผ ๊ตฌํํ๋ ํธ์ ๋๋ค
1. ๋ด ํ์ด
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class Queue {
constructor() {
this.front = null;
this.rear = null;
this.size = 0;
}
enqueue(val) {
const node = new Node(val);
if (!this.front) {
this.front = node;
this.rear = node;
} else {
this.rear.next = node;
this.rear = node;
}
return ++this.size;
}
dequeue() {
if (!this.front) return null;
const node = this.front;
if (this.front === this.rear) {
this.rear = null;
}
this.front = this.front.next;
this.size--;
return node.val;
}
}
function solution(land) {
const COL = land[0].length;
const ROW = land.length;
const dr = [0, 0, 1, -1];
const dc = [1, -1, 0, 0];
const q = new Queue();
//์์ถ๊ด์ ๋ซ์์ ๋ ๊ฐ ์ปฌ๋ผ์์ ์ ๊ทผ ๊ฐ๋ฅํ ์์ ๋ฉ์ด๋ฆฌ์ ํฌ๊ธฐ๋ฅผ ์ ์ฅํ๊ธฐ ์ํ ๋ฐฐ์ด
const oilArr = new Array(COL).fill(0);
//๋ชจ๋ ๋ฐฐ์ด์ ๋๋ฉด์ ์์ ๋ฉ์ด๋ฆฌ ์ํ
for (let r = 0; r < ROW; r++) {
for (let c = 0; c < COL; c++) {
//์์ ๊ฐ ์๋ ๋
์ผ ๊ฒฝ์ฐ ๋ค์ ์นธ์ผ๋ก ์ด๋
if (!land[r][c]) continue;
//๋ฐฉ๋ฌธํ ์ปฌ๋ผ์ ์ ์ฅํ๊ธฐ ์ํ ๋ณ์
const visitedCol = new Set();
//์์ ๋ฉ์ด๋ฆฌ์ ํฌ๊ธฐ๋ฅผ ์ ์ฅํ๊ธฐ ์ํ ๋ณ์
let oilSize = 0;
q.enqueue({ currentR: r, currentC: c });
//๋ฐฉ๋ฌธํ ์นธ์ 0์ผ๋ก ์์ ํ์ฌ ๋ฐฉ๋ฌธ์ฒ๋ฆฌ
land[r][c] = 0;
oilSize++;
visitedCol.add(c);
//ํ๊ฐ ๋น ๋๊น์ง ๋ฐ๋ณต
while (q.size) {
const { currentR, currentC } = q.dequeue();
for (let i = 0; i < 4; i++) {
const nextR = currentR + dr[i];
const nextC = currentC + dc[i];
if (
nextR >= 0 &&
nextR < ROW &&
nextC >= 0 &&
nextC < COL &&
land[nextR][nextC]
) {
q.enqueue({ currentR: nextR, currentC: nextC });
land[nextR][nextC] = 0;
oilSize++;
visitedCol.add(nextC);
}
}
}
//๋ฉ์ด๋ฆฌ์ ํฌ๊ธฐ๋ฅผ ๊ตฌํ ๋ค์, ๋ฐฉ๋ฌธํ ์ปฌ๋ผ๋ณ๋ก ์์ ๋ฉ์ด๋ฆฌ ํฌ๊ธฐ oilArr์ ๋ํด์ค
Array.from(visitedCol).forEach((c) => {
oilArr[c] += oilSize;
});
}
}
return Math.max(...oilArr);
}
'๐ง ์๊ณ ๋ฆฌ์ฆ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] ๊ณผ์ ์งํํ๊ธฐ JS (1) | 2024.01.03 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค][PCCP ๊ธฐ์ถ๋ฌธ์ ] 3๋ฒ / ์๋ ๋ก๊ทธ ์๊ณ JSํ์ด (0) | 2023.12.29 |
[๋ฐฑ์ค] 2573 ๋น์ฐ js ํ์ด (1) | 2023.12.28 |
[๋ฐฑ์ค] 7569 ํ ๋งํ js ํ์ด (1) | 2023.12.28 |
[๋ฐฑ์ค] 4179 ๋ถ! js ํ์ด (1) | 2023.12.27 |