문제 : boj21736
주어지는 값
O = 빈공간
X = 이동 불가능한 공간
P = 사람 위치
I = 도연이 위치
주어진 값들로 이루어진 배열에서 도연이가 사람을 몇명이나 만날 수 있는가.
도연이는 현재위치에서 상하좌우로만 이동이 가능하며 X공간과 주어진 공간에서 벗어날수는 없다.
코드
#include <bits/stdc++.h>
#define X first
#define Y second
using namespace std;
int dx[4] = {0,1,0,-1}; //상하 이동값
int dy[4] = {1,0,-1,0}; // 좌우 이동값
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n,m;
cin>>n>>m; // 주어진 영역 n*m
vector<string> arr; // 영역에 주어진 값을 받아 넣을 배열
queue<pair<int,int>> Q;
for(int i=0; i<n; i++){
string s; cin>>s;
arr.push_back(s);
for(int j=0; j<m; j++){
if(!Q.empty())break;
if(arr[i][j]=='I'){
Q.push({i,j}); //현재 도연이의 위치를 큐에 삽입
}
}
}
int count =0;
while(!Q.empty()){
pair<int,int> cur = Q.front(); Q.pop();
for(int i=0; i<4; i++){
int x = cur.X +dx[i];
int y = cur.Y + dy[i];
if(x<0||x>=n||y<0||y>=m)continue;
if(arr[x][y]=='X')continue;
if(arr[x][y]=='P') count++; // 사람을 만나면 카운트 +1
arr[x][y] = 'X';
Q.push({x,y});
}
}
if(count==0) cout<<"TT";
else cout<<count;
}
기본적인 bfs 문제 같다!