2589번: 보물섬
첫째 줄에는 보물 지도의 세로의 크기와 가로의 크기가 빈칸을 사이에 두고 주어진다. 이어 L과 W로 표시된 보물 지도가 아래의 예와 같이 주어지며, 각 문자 사이에는 빈 칸이 없다. 보물 지도의
www.acmicpc.net
원소가 L인 좌표를 시작점으로 하는 너비 우선 탐색을 수행하면 해당 좌표에서 가장 멀리 떨어진 'L'의 거리를 알 수 있다.
원소가 L인 모든 좌표에 대하여 너비 우선 탐색을 수행하고 그중 최댓값을 출력하면 원하는 결과를 얻을 수 있다.
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct Pos {
int y;
int x;
};
const int INF = 987654321;
int R, C;
char board[50][50];
bool visited[50][50];
int dy[4] = { 0, 0, 1, -1 };
int dx[4] = { 1, -1, 0, 0 };
int bfs(Pos start) {
queue<pair<Pos, int>> q;
q.push({ start, 0 });
visited[start.y][start.x] = true;
int ret;
while (!q.empty()) {
Pos here = q.front().first;
int dist = q.front().second;
q.pop();
ret = dist;
for (int i = 0; i < 4; i++) {
Pos there = { here.y + dy[i], here.x + dx[i] };
int nextDist = dist + 1;
if (there.y >= 0 && there.y < R && there.x >= 0 && there.x < C)
if (!visited[there.y][there.x] && board[there.y][there.x] == 'L') {
visited[there.y][there.x] = true;
q.push({ there, nextDist });
}
}
}
return ret;
}
int bfsAll() {
int ret = 0;
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++) {
if (board[i][j] == 'L') {
memset(visited, false, sizeof(visited));
ret = max(ret, bfs({ i,j }));
}
}
return ret;
}
int main(void) {
cin >> R >> C;
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
cin >> board[i][j];
cout << bfsAll() << endl;
return 0;
}
알고리즘 200일 프로젝트 - 166 day
'알고리즘 > BOJ' 카테고리의 다른 글
백준 1005번: ACM Craft (0) | 2020.09.22 |
---|---|
백준 7562번: 나이트의 이동 (0) | 2020.09.21 |
백준 16234번: 인구 이동 (0) | 2020.09.21 |
백준 1261번: 알고스팟 (0) | 2020.09.21 |
백준 10451번: 순열 사이클 (0) | 2020.09.21 |