본문 바로가기
백준 알고리즘/BFS

백준 2589번 C++

by paysmile 2019. 8. 12.

#include <iostream>
#include <queue>
#include <string>
#include <cstring>
#include <vector>

using namespace std;
const int MAX = 51;
int n, m;
int map[MAX][MAX];
vector<pair<int, int>> v;
int visited[MAX][MAX];
struct Move {
	int x, y;
};
Move mv[4] = { {1,0}, {0,1}, {-1,0}, {0,-1} };

int bfs(int i, int j) {
	int answer = 0;
	memset(visited, -1, sizeof(visited));

	queue<pair<int, pair<int,int>>> way;
	way.push(make_pair(i,make_pair(j,0)));
	visited[i][j] = 1;

	while (!way.empty()) {
		int currenti = way.front().first;
		int currentj = way.front().second.first;
		answer = way.front().second.second;
		way.pop();

		for (int k = 0; k < 4; k++) {
			int movei = currenti + mv[k].x;
			int movej = currentj + mv[k].y;
			
			if (movei >= 0 && movei < n && movej >= 0 && movej < m) {
				if (visited[movei][movej] == -1 && map[movei][movej] == 1) {
					visited[movei][movej] = 1;
					way.push(make_pair(movei, make_pair(movej, answer + 1)));
				}
			}
		}
	}
	return answer;
}

int main(void) {
	cin >> n >> m;
	string s;
	int answer = 0;

	for (int i = 0; i < n; i++) {
		cin >> s;
		for (int j = 0; j < m; j++) {
			if (s[j] == 'L') {
				v.push_back(make_pair(i, j));
				map[i][j] = 1;
			}
			else
				map[i][j] = 0;
		}
	}
	for (int i = 0; i < v.size(); i++) {
		answer = max(answer,bfs(v[i].first, v[i].second));
	}
	cout << answer << endl;
	return 0;
}

'백준 알고리즘 > BFS' 카테고리의 다른 글

백준 1707번 C++  (0) 2019.08.14
백준 5014번 C++  (0) 2019.08.12
백준 7569번 C++  (0) 2019.08.10
백준 2468번 C++  (0) 2019.08.10
백준 11403번 C++  (0) 2019.08.08