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<int, int>> 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 |
반응형