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;
}
๊ฒฐ๊ณผ
๋ฐ์ํ