본문 바로가기
PS/BOJ

[백준] 21736. 헌내기는 친구가 필요해(c++)

by backend 개발자 지망생 2024. 12. 16.

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

전형적인 bfs 문제였다.
문자열을 입력받는 방법을 다시 리마인드 할 수 있어 좋았다.


#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
#include <string>
#include <cstring>
#include <deque>
#include <climits>
#include <set>
#include <stack>
#include <tuple>
#include <unordered_map>
#include <sstream>
using namespace std;

using ll = long long;

void init() {
    cin.tie(0);
    cout.tie(0);
    ios_base::sync_with_stdio(false);
}

char arr[601][601];
bool visited[601][601];

int answer = 0;
int n, m;

int dx[4] = { 0,0,-1,1 };
int dy[4] = { 1,-1,0,0 };

void bfs(int startY, int startX) {

    visited[startY][startX] = true;
    queue<pair<int, int>> q;

    q.push(make_pair(startY, startX));

    while (!q.empty()) {
        int y = q.front().first;
        int x = q.front().second;

        q.pop();

        for (int i = 0; i < 4; i++) {
            int ny = y + dy[i];
            int nx = x + dx[i];

            if (ny >= 0 && nx >= 0 && ny < n && nx < m && !visited[ny][nx] && arr[ny][nx] != 'X') {
                if (arr[ny][nx] == 'P')
                    answer++;
                visited[ny][nx] = true;
                q.push(make_pair(ny, nx));
            }
        }
    }
}

int main() {

    init();

    int startX;
    int startY;

    cin >> n >> m;

    for (int i = 0; i < n; i++) {
        cin >> arr[i];

        for (int j = 0; j < m; j++) {
            if (arr[i][j] == 'I') {
                startX = j;
                startY = i;
            }
        }
    }

    bfs(startY, startX);

    if (answer == 0) {
        cout << "TT";
    }
    else {
        cout << answer;
    }


    return 0;
}

'PS > BOJ' 카테고리의 다른 글

[백준] 18111. 마인크래프트(c++)  (0) 2024.12.19
[백준] 30804. 과일 탕후루(c++)  (0) 2024.12.18
[백준] 15654. N과 M (5)(c++)  (0) 2024.04.29
[백준] 1469. 숌 사이 수열(c++)  (1) 2024.04.29
[백준] 15652. N과 M (4)(c++)  (0) 2024.04.28