반응형
https://www.acmicpc.net/problem/2589
2589번: 보물섬
첫째 줄에는 보물 지도의 세로의 크기와 가로의 크기가 빈칸을 사이에 두고 주어진다. 이어 L과 W로 표시된 보물 지도가 아래의 예와 같이 주어지며, 각 문자 사이에는 빈 칸이 없다. 보물 지도의
www.acmicpc.net
[ 문제풀이 ]
1. 모든 좌표에서 bfs를 통해 가장 먼 땅까지의 거리를 return 합니다.
2. 그 값들 중 가장 큰 값을 출력합니다.
[ 소스코드 ]
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 | #include<iostream> #include<queue> using namespace std; int N, M; char arr[51][51]; int dy[4] = { -1,1,0,0 }; int dx[4] = { 0,0,-1,1 }; struct node { int y; int x; int cnt; }; int bfs(int y, int x) { int ret = 0; int visited[50][50] = { 0 }; queue<node> q; q.push({ y,x,0 }); while (!q.empty()) { const int y = q.front().y; const int x = q.front().x; const int cnt = q.front().cnt; q.pop(); if (visited[y][x] == 1) continue; visited[y][x] = 1; ret = max(ret, cnt); for (int i = 0; i < 4; i++) { const int yy = y + dy[i]; const int xx = x + dx[i]; if (yy >= 0 && yy < N && xx >= 0 && xx < M) { if (visited[yy][xx] != 1 && arr[yy][xx] == 'L') { q.push({ yy,xx,cnt + 1 }); } } } } return ret; } int main() { scanf("%d %d", &N, &M); for (int i = 0; i < N; i++) { scanf("%s", &arr[i]); } int ans = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (arr[i][j] == 'L') { ans = max(ans, bfs(i, j)); } } } printf("%d", ans); } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 2268번 - 수들의 합 7 (C++) (0) | 2022.12.29 |
---|---|
[ 백준 ] 1194번 - 달이 차오른다, 가자. (C++) (0) | 2022.12.28 |
[ 백준 ] 23793번 - 두 단계 최단 경로 1 (C++) (0) | 2022.12.26 |
[ 백준 ] 1759번 - 암호 만들기 (C++) (0) | 2022.12.25 |
[ 백준 ] 19538번 - 루머 (C++) (0) | 2022.12.24 |