백준 algorithm
백준 1012 유기농 배추 C++ (BFS)
cosmohoo
2022. 7. 21. 23:31
반응형
입력
입력의 첫 줄에는 테스트 케이스의 개수 T가 주어진다. 그 다음 줄부터 각각의 테스트 케이스에 대해 첫째 줄에는 배추를 심은 배추밭의 가로길이 M(1 ≤ M ≤ 50)과 세로길이 N(1 ≤ N ≤ 50), 그리고 배추가 심어져 있는 위치의 개수 K(1 ≤ K ≤ 2500)이 주어진다. 그 다음 K줄에는 배추의 위치 X(0 ≤ X ≤ M-1), Y(0 ≤ Y ≤ N-1)가 주어진다. 두 배추의 위치가 같은 경우는 없다.
출력
각 테스트 케이스에 대해 필요한 최소의 배추흰지렁이 마리 수를 출력한다.
예제 입력 1 복사
2
10 8 17
0 0
1 0
1 1
4 2
4 3
4 5
2 4
3 4
7 4
8 4
9 4
7 5
8 5
9 5
7 6
8 6
9 6
10 10 1
5 5
예제 출력 1 복사
5
1
예제 입력 2 복사
1
5 3 6
0 2
1 2
2 2
3 2
4 2
4 0
예제 출력 2 복사
2
=> BFS 혹은 DFS로 풀수 있는 문제였습니다.
=> 저는 '시간초과'에 걸려 한없이 오랜 시간동안 풀었습니다.
=> BFS부문에서 틀린 줄 알았으나, 초기화하는 부문에서 틀렸었습니다. (init함수)
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <utility>
#include <stdio.h>
#include <cmath>
using namespace std;
int mp[51][51] = {0, };
bool visitied[51][51] = { false, };
int M, N, K;
int dx[4] = { 0,1,0,-1 };//인접한 곳만 갈 수 있도록 하는 변수
int dy[4] = { 1,0,-1,0 };
queue<pair<int, int>> que;
int answer=0;
void BFS(int x, int y)
{
que.push(make_pair(x,y));
while(!que.empty())
{
int tmpx = que.front().first;
int tmpy = que.front().second;
// visitied[tmpx][tmpy] = true;
que.pop();
for(int i=0; i<4; i++)
{
int nx = tmpx + dx[i];
int ny = tmpy + dy[i];
if((!visitied[nx][ny]) && (nx >= 0) && (nx < N) && (ny >= 0) && (ny < M) && (mp[nx][ny]==1))
{
visitied[nx][ny] = true;
que.push(make_pair(nx,ny));
}
}
}
}
void init(int N, int M)
{
while(!que.empty())que.pop();
for(int i =0; i<N; i++)
{
for(int j=0; j<M; j++)
{
mp[i][j]=0;
visitied[i][j]=false;
}
}
answer = 0;
}
int main() {
int T;
cin >> T;
while (T > 0)
{
init(N,M);
cin >> M >> N >> K;
//mp 초기화하기
for (int i = 0; i < K; i++)
{
int x; int y;
cin >> x >> y;
mp[y][x] = 1;
}
for(int i=0; i<N; i++)
{
for(int j=0; j<M; j++)
{
if((mp[i][j]==1) && (!visitied[i][j]))
{
visitied[i][j]=true;
answer++;
BFS(i,j);
}
}
}
cout<<answer<<'\n';
T--;
}
}
반응형