[백준] 2589 보물섬

0

백준

목록 보기
254/271
post-thumbnail

[백준] 2589 보물섬

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

int h, w;
vector<string> board;

int answer = 0;

int dirR[4] = { 0, 0, 1, -1 };
int dirC[4] = { 1, -1, 0, 0 };

bool inRange(int r, int c) {
	if ((r < 0) || (r >= h)) return false;
	if ((c < 0) || (c >= w)) return false;
	return true;
}

void bfs(int startR, int startC) {
	//<좌표, 이동한 거리>
	queue<pair<pair<int, int>, int>> q;
	int visited[51][51] = { 0 };

	q.push({ {startR, startC}, 0 });
	while (!q.empty()) {
		int curR = q.front().first.first;
		int curC = q.front().first.second;
		int curDist = q.front().second;
		q.pop();

		if (visited[curR][curC]) continue;
		visited[curR][curC] = 1;

		answer = max(answer, curDist);

		for (int d = 0; d < 4; ++d) {
			int nextR = curR + dirR[d]; 
			int nextC = curC + dirC[d];
			if (!inRange(nextR, nextC)) continue;
			if (board[nextR][nextC] == 'W') continue;

			q.push({ {nextR, nextC}, curDist + 1 });
		}
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);

	cin >> h >> w;
	for (int i = 0; i < h; ++i) {
		string input;
		cin >> input;
		board.push_back(input);
	}

	for (int i = 0; i < h; ++i) {
		for (int j = 0; j < w; ++j) {
			if (board[i][j] == 'W') continue;

			bfs(i, j);
		}
	}

	cout << answer;
	return 0;
}

profile
Be able to be vulnerable, in search of truth

0개의 댓글