본문 바로가기

알고리즘/BOJ

2589번

2589번 - 보물섬


모든 육지에 대해서 BFS를 실행한다. 가장 멀리 떨어진 값을 ans 변수에 넣는다.


각 육지에서 가장 떨어진 값을 찾으면 되기 때문에, 각 점에서 마다 BFS를 실행시킨다.


<정답 코드>


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<iostream>
#include<queue>
using namespace std;
int n, m;
int ans = -1;
char map[51][51];
int dx[4= { 0,0,1,-1 };
int dy[4= { 1,-1,0,0 };
 
void bfs(int x, int y)
{
    int dist[51][51= { 0, };
    queue<pair<intint>> q;
    q.push({ x,y });
 
    while (!q.empty())
    {
        x = q.front().first;
        y = q.front().second;
        q.pop();
 
        for (int d = 0; d < 4; d++)
        {
            int nx = x + dx[d];
            int ny = y + dy[d];
            if (nx >= 0 && ny >= 0 && nx < n && ny < m && dist[nx][ny]==0 && map[nx][ny] == 'L')
            {
                dist[nx][ny] = dist[x][y] + 1;
                q.push({ nx,ny });
            }
        }
    }
 
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (dist[i][j] > ans)
            {
                ans = dist[i][j];
            }
        }
    }
 
}
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
 
    
    cin >> n >> m;
 
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> map[i][j];
        }
    }
 
    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;
}
cs


반응형

'알고리즘 > BOJ' 카테고리의 다른 글

1813번  (0) 2018.03.07
2206번  (0) 2018.03.07
7562번  (0) 2018.03.07
1244. 최대 상금  (0) 2018.03.06
1074번  (0) 2018.02.28