Hello Ocean! ๐ŸŒผ

[๋ฐฑ์ค€/C++] 2589. ๋ณด๋ฌผ์„ฌ ๋ณธ๋ฌธ

Algorithm

[๋ฐฑ์ค€/C++] 2589. ๋ณด๋ฌผ์„ฌ

bba_dda 2021. 5. 19. 11:49
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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

์œก์ง€์™€ ๋ฐ”๋‹ค๋กœ ์ด๋ฃจ์–ด์ง„ nxm ๋งต์—์„œ 

์œก์ง€์—์„œ ์‹œ์ž‘ํ•ด์„œ, ๋ฐ”๋‹ค๋ฅผ ๊ฑฐ์น˜์ง€ ์•Š๊ณ  ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ๋จผ ์œก์ง€๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. 

ํ’€์ด

BFS๋ฅผ ์ด์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค! ๋˜ํ•œ, ๋ชจ๋“  ์œก์ง€๊ฐ€ ์‹œ์ž‘์ ์ด ๋  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์™„์ „ํƒ์ƒ‰์ด๊ธฐ๋„ ํ•˜๋‹ค. 

๋ชจ๋“  ์œก์ง€์—์„œ BFS๋ฅผ ๋Œ๋ ค์„œ, ๋‹ค๋ฅธ ์œก์ง€๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๋ชจ๋‘ ๊ตฌํ•ด์„œ ๊ทธ ์ค‘์— ์ตœ๋Œ“๊ฐ’์„ ์ถœ๋ ฅํ–ˆ๋‹ค.

์ฝ”๋“œ

#include <iostream>
#include <queue>

using namespace std;

int dr[4] = { -1,1,0,0 };
int dc[4] = { 0,0,-1,1 };
int map[52][52] = { 0, };
int cache[52][52] = { 0, };
int max_dist = 0;

void BFS(int r, int c) {
	queue<pair<int, int>> q;
	q.push(make_pair(r, c));
	
	cache[r][c] = 1;
	while (!q.empty()) {
		int temp_r = q.front().first;
		int temp_c = q.front().second;
		q.pop();

		max_dist = max(max_dist, cache[temp_r][temp_c]);
		for (int i = 0;i < 4;i++) {
			int next_r = temp_r + dr[i];
			int next_c = temp_c + dc[i];
			if (map[next_r][next_c] == 1 && cache[next_r][next_c] == 0) {
				q.push(make_pair(next_r, next_c));
				cache[next_r][next_c] = cache[temp_r][temp_c] + 1;
			}
		}
	}
}
int main(void) {
	int R, C;
	cin >> R >> C;
	for (int r = 1;r <= R;r++) {
		for (int c = 1;c <= C;c++) {
			char temp;
			cin >> temp;
			if (temp == 'W') map[r][c] = 0;
			else map[r][c] = 1;
		}
	}
	for (int r = 1;r <= R;r++) {
		for (int c = 1;c < C;c++) {
			if (map[r][c] == 1) { ////
				fill(&cache[0][0], &cache[51][52], 0); /////
				BFS(r, c);
			}
			
		}
	}
	cout << max_dist -1 << endl;
}

๊ฒฐ๊ณผ

๋ฐ˜์‘ํ˜•