본문 바로가기

Algorithm/BAEKJOON

[BOJ] 2589번 보물섬 (C++)

728x90
반응형

https://www.acmicpc.net/problem/2589

 

2589번: 보물섬

보물섬 지도를 발견한 후크 선장은 보물을 찾아나섰다. 보물섬 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 각 칸은 육지(L)나 바다(W)로 표시되어 있다. 이 지도에서

www.acmicpc.net

 

#include <iostream>
#include <queue>
using namespace std;

int n, m;
char arr[50][50];
int path[50][50] = {-1, };
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
int maxlen = 0;

void bfs(int x, int y){
	queue<pair<int, int>> q;
	q.push({x, y});
	path[x][y] = 0;
	
	while(!q.empty()){
		int x = q.front().first;
		int y = q.front().second;
		q.pop();
		
		for(int i = 0; i < 4; i++){
			int nx = x + dx[i];
			int ny = y + dy[i];
			
			if(!(nx >= 0 && nx < n && ny >= 0 && ny < m)) continue;
			
			if(path[nx][ny] == -1 && arr[nx][ny] == 'L'){
				path[nx][ny] = path[x][y] + 1;
				q.push({nx, ny});
				if(maxlen < path[nx][ny]) maxlen = path[nx][ny];
			}
		}
	}
}

void reset(){
	maxlen = 0;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++){
			path[i][j] = -1;
		}
	}
}

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 >> arr[i][j];
		}
	}
	
	// 모든 'L'에 대하여 bfs 실행
	int answer = 0;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++){
			if(arr[i][j] == 'L') {
				bfs(i, j);
				if(maxlen > answer) answer = maxlen;
				reset();
			}
		}
	}
	cout << answer << endl;
	return 0;
}
728x90
반응형

'Algorithm > BAEKJOON' 카테고리의 다른 글

[BOJ] 11123번 양 한마리... 양 두마리... (C++)  (0) 2022.04.30
[BOJ] 3184번 양 (C++)  (0) 2022.04.30
[BOJ] 2636번 치즈 (C++)  (0) 2022.04.29
[BOJ] 20300번 서강근육맨 (C++)  (0) 2022.04.29
[BOJ] 12813번 이진수 연산 (C++)  (0) 2022.03.07