hades

[Baekjoon] 2638๋ฒˆ: ์น˜์ฆˆ ๋ณธ๋ฌธ

๐Ÿ‘Š PS/Algorithm

[Baekjoon] 2638๋ฒˆ: ์น˜์ฆˆ

hades1 2024. 8. 13. 20:39

๐Ÿฅ… ๋ฌธ์ œ

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

 

๐Ÿ” ์„ค๊ณ„

์น˜์ฆˆ๊ฐ€ ๋‹ฟ์•„์žˆ๋Š” ๋ธ”๋Ÿญ์ด 2๊ฐœ ์ด์ƒ์ด๋ฉด ๋…น์„ ์˜ˆ์ •์ด๋‹ค. ์น˜์ฆˆ ๋‚ด๋ถ€์— ์žˆ๋Š” ๊ณต๊ธฐ๋Š” ์น˜์ฆˆ์— ์˜ํ–ฅ์„ ์ค„ ์ˆ˜ ์—†๋‹ค. ๋ชจ๋ˆˆ์ข…์ด์˜ ๋งจ ๊ฐ€์žฅ์ž๋ฆฌ๋“ค์€ ์น˜์ฆˆ๊ฐ€ ๋†“์ด์ง€ ์•Š๋Š”๋‹ค๊ณ  ํ–ˆ์œผ๋ฏ€๋กœ, ๊ทธ ์ค‘ ๋Œ€ํ‘œ์ ์ธ (0, 0) ์—์„œ ์‹œ์ž‘ํ•˜์—ฌ ์™ธ๋ถ€ ๊ณต๊ธฐ์˜ ์˜ํ–ฅ๋ ฅ์„ ํ–‰์‚ฌํ•œ๋‹ค. 

 

์™ธ๋ถ€ ๊ณต๊ธฐ์˜ ์˜ํ–ฅ๋ ฅ์„ ํ–‰์‚ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€ BFS๋ฅผ ์ด์šฉํ•˜์—ฌ ์น˜์ฆˆ๊ฐ€ ๋†“์ธ ๊ณณ์— 2๋ฒˆ ๋ฐฉ๋ฌธํ–ˆ์„ ๋•Œ, 1์‹œ๊ฐ„ ํ›„์— ๋…น์œผ๋ฉด์„œ ์ƒˆ๋กญ๊ฒŒ ์˜ํ–ฅ๋ ฅ์„ ํ–‰์‚ฌํ•  ์ˆ˜ ์žˆ๋Š” ์™ธ๋ถ€ ๊ณต๊ธฐ ํ›„๋ณด๋“ค์˜ ๋ชจ์ž„์ธ next_q์— ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ๋งŒ์•ฝ next_q์— ์•„๋ฌด๊ฒƒ๋„ ์ถ”๊ฐ€๋˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ๊ทธ๋Œ€๋กœ ์ข…๋ฃŒ๋˜๊ณ , ์ถ”๊ฐ€๋œ ๊ฒƒ์ด ์žˆ๋‹ค๋ฉด 1์ดˆ๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค. next_q์— ์ถ”๊ฐ€ํ•˜๋Š” ์ด์œ ๋Š” ์น˜์ฆˆ๊ฐ€ ๋…น๋Š” ๊ณผ์ •์€ 1์‹œ๊ฐ„ ํ›„์— ๋™์‹œ์— ์ด๋ฃจ์–ด์ ธ์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ๋„ ์žˆ๋‹ค.

 

๐Ÿ‘Š ํ’€์ด

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

int n, m, result = 0;
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
vector<vector<int>> paper(100, vector<int>(100));
vector<vector<int>> visited(100, vector<int>(100));

void bfs() {
	queue<pair<int, int>> q;
	queue<pair<int, int>> next_q;
	q.push({ 0, 0 });
	visited[0][0] = 1;

	while (true) {
		while (!q.empty()) {
			int cur_x = q.front().first;
			int cur_y = q.front().second;
			q.pop();
			for (int i = 0; i < 4; i++) {
				int new_x = cur_x + dx[i];
				int new_y = cur_y + dy[i];
				if (!(new_x >= 0 && new_x < n && new_y >= 0 && new_y < m)) {
					continue;
				}
				if (paper[new_x][new_y] == 0 && visited[new_x][new_y] == 0) {
					visited[new_x][new_y] += 1;
					q.push({ new_x, new_y });
				}
				else if (paper[new_x][new_y] == 1) {
					visited[new_x][new_y] += 1;
					if (visited[new_x][new_y] == 2) {
						next_q.push({ new_x, new_y });
					}
				}
			}
		}
		if (next_q.empty()) {
			break;
		}
		else {
			result += 1;
		}

		while (!next_q.empty()) {
			int new_x = next_q.front().first;
			int new_y = next_q.front().second;
			q.push(next_q.front());
			next_q.pop();
			paper[new_x][new_y] = 0;
		}
	}
	
	
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> n >> m;

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> paper[i][j];
		}
	}

	bfs();

	cout << result << "\n";
	
	return 0;
}