1일1알

백준 21736번 헌내기는 친구가 필요해 C++ 본문

알고리즘

백준 21736번 헌내기는 친구가 필요해 C++

영춘권의달인 2022. 3. 4. 12:28

출처 : https://www.acmicpc.net/problem/21736

 

간단한 그래프 탐색 문제이다. bfs를 이용해서 문제를 해결하였다.

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>

using namespace std;
using ll = long long;

int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };

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

	int n, m;
	cin >> n >> m;
	pair<int, int> start;
	vector<vector<char>> board(n, vector<char>(m));
	vector<vector<bool>> found(n, vector<bool>(m, false));
	for (int i = 0; i < n; i++) {
		string str;
		cin >> str;
		for (int j = 0; j < m; j++) {
			board[i][j] = str[j];
			if (board[i][j] == 'I') start = { i,j };
		}
	}
	int ans = 0;
	queue<pair<int, int>> q;
	q.push(start);
	found[start.first][start.second] = true;
	while (!q.empty()) {
		auto curr = q.front();
		q.pop();
		if (board[curr.first][curr.second] == 'P') ans++;
		for (int i = 0; i < 4; i++) {
			int nextRow = curr.first + dRow[i];
			int nextCol = curr.second + dCol[i];
			if (nextRow < 0 || nextRow >= n) continue;
			if (nextCol < 0 || nextCol >= m) continue;
			if (board[nextRow][nextCol] == 'X') continue;
			if (found[nextRow][nextCol]) continue;
			q.push({ nextRow,nextCol });
			found[nextRow][nextCol] = true;
		}
	}
	if (ans == 0) cout << "TT";
	else cout << ans;
};

'알고리즘' 카테고리의 다른 글

백준 12892번 생일 선물 C++  (0) 2022.03.06
백준 10472번 십자뒤집기 C++  (0) 2022.03.05
백준 2479번 경로 찾기 C++  (0) 2022.03.03
백준 12886번 돌 그룹 C++  (0) 2022.03.02
백준 2617번 구슬 찾기 C++  (0) 2022.03.01