[BOJ / C++] 21736 : 헌내기는 친구가 필요해

Taegang Yun·2023년 9월 13일
1

문제 바로가기

21736 : 실버 2

💡 생각

그냥 bfs 문제다. 벽을 만나면 그만 가고, 도연이 위치를 start로 해놓은 다음 만나느느 P 수를 세면 되는 거다.

🖥️ 소스코드

#define fastio ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <string.h>
using namespace std;

/* Method Initialization */
void input();
void solve();
void bfs(int y, int x);
/* Variable Initialization */
int n, m, res;
string str;
pair<int, int> start;
char a[604][604];
int visited[604][604];

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



int main()
{
    fastio;
    input();
    solve();
    return 0;
}

void input()
{
    cin >> n >> m;
    for(int i = 0 ; i < n; i++)
    {
        cin >> str;
        for(int j = 0; j < str.size(); j++)
        {
            a[i][j] = str[j];
            if(a[i][j] == 'I')  start = {i, j};
        }
    }
}

void solve()
{
    bfs(start.first, start.second);
    if(res == 0) {
        cout << "TT" << '\n';
        return;
    }
    cout << res << '\n';
}

void bfs(int y, int x)
{
    queue<pair<int, int>> q;
    q.push({y, x});
    visited[y][x] = 1;
    while(q.size()){
        tie(y, x) = q.front(); 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) continue;
            if(a[ny][nx] == 'X' || visited[ny][nx]) continue;
            visited[ny][nx]  = visited[y][x] + 1;
            if(a[ny][nx] == 'P') res++;
            q.push({ny, nx});
        }
    }
}

1트 성공!!

profile
언젠간 전문가가 되겠지

0개의 댓글