[C++] 백준/Gold/2589. 보물섬

2025. 2. 13. 21:01·C++/Algorithm

문제: 보물섬(백준 2589번)

문제 분석

지도 상에 있는 땅('L')과 물('W')이 주어질 때, 모든 땅에서 출발하여 가장 멀리 떨어진 땅까지의 최단 거리를 구하는 문제다. 즉, 모든 땅을 시작점으로 BFS를 수행하여 최대 이동 거리를 계산한 후 그 중 가장 큰 값을 출력하면 된다.


문제의 핵심은 다음과 같다.

BFS를 사용해 각 땅에서의 최대 거리를 계산

  • 맵 상에서 땅('L')에서 시작해 상하좌우로 이동하며, 각 칸까지 도달하는 최소 이동 횟수를 구한다.

모든 땅을 시작점으로 탐색

  • 물('W')는 탐색 대상이 아니므로 건너뛴다.
  • 최대 이동 횟수를 찾는다.

BFS

역할:

주어진 시작점에서 BFS를 수행하여, 도달할 수 있는 모든 땅까지의 최단 거리를 계산하고, 그 중 최대 거리를 반환한다.

동작:

  • depth 배열을 통해 각 칸까지의 이동 횟수를 기록한다.
  • 상하좌우 이동하면서, 범위를 벗어나지 않고 땅('L')일 경우만 탐색한다.
  • BFS 과정 중 최댓값을 업데이트하여 result에 저장한다.

전체 코드

#include <bits/stdc++.h>
using namespace std;

int n, m;
vector<string> board;
int offset[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };

int BFS(pair<int, int> start) {
	int result = 0;
	vector<vector<int>> depth(n, vector<int>(m, -1));
	queue<pair<int, int>> bfs;
	bfs.push(start);
	depth[start.first][start.second] = 0;
	while (!bfs.empty()) {
		int x, y; tie(y, x) = bfs.front();
		bfs.pop();

		if (result < depth[y][x]) {
			result = depth[y][x];
		}

		for (int i = 0; i < 4; i++) {
			int xx = x + offset[i][0];
			int yy = y + offset[i][1];
			if (xx < 0 || xx >= m || yy < 0 || yy >= n)continue;
			if (depth[yy][xx] == -1 && board[yy][xx] == 'L') {
				bfs.push({ yy, xx });
				depth[yy][xx] = depth[y][x] + 1;
			}
		}
	}
	return result;
}

int main() {
	ios::sync_with_stdio(0); cin.tie(0);
	cin >> n >> m;
	board.resize(n);
	
	for (int i = 0; i < n; i++) {
		cin >> board[i];
	}
	int answer = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (board[i][j] == 'W')continue;
			int result = BFS({ i, j });
			answer = max(answer, result);
		}
	}
	cout << answer;
}

'C++ > Algorithm' 카테고리의 다른 글

[C++] 백준/Gold/9205. 맥주 마시면서 걸어가기  (1) 2025.02.17
[C++] 백준/Gold/10942. 팰린드롬?  (0) 2025.02.14
[C++] 백준/Gold/1339. 단어 수학  (0) 2025.02.12
[C++] 백준/Gold/3055. 탈출  (0) 2025.02.11
[C++] 백준/Gold/2042. 구간 합 구하기  (0) 2025.02.10
'C++/Algorithm' 카테고리의 다른 글
  • [C++] 백준/Gold/9205. 맥주 마시면서 걸어가기
  • [C++] 백준/Gold/10942. 팰린드롬?
  • [C++] 백준/Gold/1339. 단어 수학
  • [C++] 백준/Gold/3055. 탈출
돼지표
돼지표
https://github.com/wkdgns135
  • 돼지표
    돼지표 개발 스토리
    돼지표
  • 전체
    오늘
    어제
    • 분류 전체보기 (97)
      • C++ (58)
        • Algorithm (52)
      • Python (1)
      • Machine Learning (2)
      • Computer Graphics (4)
        • Curly Hair Simulation (2)
      • GPU Programming (11)
        • CUDA basic (7)
        • CUDA fluidsGL (4)
      • Unreal 5 (19)
        • Troubleshooting (4)
        • FPS Shooting (5)
        • Study (8)
        • EOS (1)
      • Computer Science (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    UE5
    구현
    아이작 맵 생성
    GPU Programming
    그래프 이론
    BFS
    그래프 탐색
    Algorithm
    C++
    Rendering Pipeline
    dp
    FPS
    Fluid Simulation
    위상 정렬
    unreal 5
    OpenGL
    자료 구조
    CUDA
    그리디 알고리즘
    수학
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
돼지표
[C++] 백준/Gold/2589. 보물섬
상단으로

티스토리툴바