티스토리 뷰

https://www.acmicpc.net/problem/2573

 

2573번: 빙산

첫 줄에는 이차원 배열의 행의 개수와 열의 개수를 나타내는 두 정수 N과 M이 한 개의 빈칸을 사이에 두고 주어진다. N과 M은 3 이상 300 이하이다. 그 다음 N개의 줄에는 각 줄마다 배열의 각 행을

www.acmicpc.net

class Node {
	constructor(item) {
		this.item = item;
		this.next = null;
	}
}

class Queue {
	constructor() {
		this.head = null;
		this.tail = null;
		this.length = 0;
	}

	push(item) {
		const node = new Node(item);
		if (this.head == null) {
			this.head = node;
		} else {
			this.tail.next = node;
		}

		this.tail = node;
		this.length += 1;
	}

	pop() {
		const popItem = this.head;
		this.head = this.head.next;
		this.length -= 1;
		return popItem.item;
	}
}
const fs = require('fs');
const input = fs
	.readFileSync('./dev/stdin')
	.toString()
	.trim()
	.split('\n')
	.map((v) => v.split(' ').map(Number));
const [N, M] = input.shift();

let icebug = input.map((v) => [...v]);
let time = 0;
const dx = [0, 0, -1, 1];
const dy = [-1, 1, 0, 0];

while (true) {
	// 두덩어리로 분리되는지 확인.
	let checkTwo = icebug.map((v) => [...v]);
	let cnt = 0;
	for (let i = 0; i < N; i++) {
		for (let j = 0; j < M; j++) {
			if (checkTwo[i][j] != 0) {
				cnt++;
				const q = new Queue();
				q.push([i, j]);
				while (q.length > 0) {
					const [x, y] = q.pop();
					for (let k = 0; k < 4; k++) {
						const nx = x + dx[k];
						const ny = y + dy[k];
						if (nx < 0 || nx >= N || ny < 0 || ny >= M || checkTwo[nx][ny] == 0)
							continue;

						checkTwo[nx][ny] = 0;
						q.push([nx, ny]);
					}
				}
			}
		}
	}
	if (cnt > 1) {
		break;
	}

	// 녹이기
	let newIcebug = Array.from(Array(N), () => Array(M).fill(0));
	for (let i = 0; i < N; i++) {
		for (let j = 0; j < M; j++) {
			if (icebug[i][j] == 0) {
				for (let k = 0; k < 4; k++) {
					const ni = i + dx[k];
					const nj = j + dy[k];
					if (ni < 0 || ni >= N || nj < 0 || nj >= M) continue;
					newIcebug[ni][nj]--;
				}
			}
		}
	}
	for (let i = 0; i < N; i++) {
		for (let j = 0; j < M; j++) {
			icebug[i][j] = icebug[i][j] + newIcebug[i][j] >= 0 ? icebug[i][j] + newIcebug[i][j] : 0;
		}
	}

	// 다녹았는지 확인
	let melt = true;
	for (let i = 0; i < N; i++) {
		for (let j = 0; j < M; j++) {
			if (icebug[i][j] != 0) {
				melt = false;
				break;
			}
		}
		if (!melt) break;
	}

	if (melt) {
		time = 0;
		break;
	}
	time++;
}

console.log(time);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함