티스토리 뷰

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

 

2589번: 보물섬

보물섬 지도를 발견한 후크 선장은 보물을 찾아나섰다. 보물섬 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 각 칸은 육지(L)나 바다(W)로 표시되어 있다. 이 지도에서

www.acmicpc.net

BFS로 풀이하였습니다. 모든 L 에서 인접한 L까지의 거리를 비교한 최대값이 답이 됩니다.


C++ 소스 코드

#include <iostream>
#include <string>
#include <queue>
#include <algorithm>
#define MAX 51
using namespace std;
int n,m,ans;
const int dx[] = {0,0,-1,1},dy[]={-1,1,0,0};
string map[MAX];
bool visit[MAX][MAX];
void bfs(int x, int y){
    queue<pair<int, int> > q;
    q.push(make_pair(x,y));
    int d = 0;
    fill(&visit[0][0],&visit[n][m]+1,0);
    visit[x][y] = true;
    while(!q.empty()){
        int qS = q.size();
        ans = max(ans,d);
        while(qS--){
            int x = q.front().first;
            int y = q.front().second;
            q.pop();
            for(int i=0;i<4;i++){
                int nx = x+dx[i], ny = y+dy[i];
                if (nx < 0 || nx >= n || ny <0 || ny>=m)continue;
                if(map[nx][ny]=='W' || visit[nx][ny]) continue;
                q.push(make_pair(nx,ny));
                visit[nx][ny] = true;
            }
        }
        d++;
    }
}
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin >> n >> m;
    for(int i=0;i<n;i++){
        cin >> map[i];
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(map[i][j] == 'L'){
                bfs(i,j);
            }
        }
    }
    cout << ans << '\n';
    return 0;
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/10   »
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
글 보관함