백준 2589 - 보물섬 - BFS

Byungwoong An·2021년 6월 9일
0

문제


문제링크 : https://www.acmicpc.net/problem/2589

풀이전략

  1. 지도의 가로와 세로의 크기는 50이하이다. 따라서 모든 L을 한번씩 BFS를 하여도 충분한 시간과 공간이다.
  2. 따라서 모든점에서 모든점으로 가는 값들 중 최대값을 찾아주면 된다.

코드

#include<bits/stdc++.h>

using namespace std;

int R, C;
char mp[52][52];
bool ch[51][51];

int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};

struct hok{
    int r, c, dis;
    hok(int aa, int bb, int cc){
        r = aa;
        c = bb;
        dis = cc;
    }
};

int bfs(int r, int c){
    memset(ch, false, sizeof(ch));
    queue<hok> q;
    q.push(hok(r, c, 0));
    ch[r][c] = true;
    int res = 0;
    while(!q.empty()){
        
        hok ret = q.front();
        if(res < ret.dis) res = ret.dis;
        q.pop();

        for(int i=0; i<4; i++){
            int rr = ret.r+dy[i];
            int cc = ret.c+dx[i];

            if(!ch[rr][cc] && mp[rr][cc] =='L'){
                ch[rr][cc] = true;
                q.push(hok(rr,cc,ret.dis+1));
            }
        }

    }

    return res;
}


int main(){
    ios_base::sync_with_stdio(false);
    // freopen("../input.txt","rt",stdin);
    
    cin >> R >> C;

    for(int i=1; i<=R; i++){
        for(int j=1; j<=C; j++){
            cin >> mp[i][j];
        }
    }
    int res = 0;
    for(int i=1; i<=R; i++){
        for(int j=1; j<=C; j++){
            if(mp[i][j] == 'L'){
                res = max(res,bfs(i,j));
            }
        }
    }
    cout<<res<<endl;
    return 0;
}


소감

시간복잡도 공간복잡도에 대한 개념만 조금 있으면 손쉽게 해결할수있었다. 가끔은 시간이 충분하면 모든것을 다 탐색하는것도 필요하다는 것을 잊지 말아야한다.

profile
No Pain No Gain

0개의 댓글