BOJ 1012 : 유기농 배추 본문
BFS/DFS를 사용하는 문제.
BFS를 사용하였다.
입력을 받은 후 전체 맵을 탐색하면서 배추가 있는 부분부터 BFS를 사용하여 배추 한 덩어리를 찾고, 한 덩어리당 배추흰지렁이 갯수를 늘리면 된다.
BFS를 사용하는 것은 동일하지만, 좌표를 큐에 넣어야 하기때문에 pair를 사용한다.
또한 좌표가 맵을 벗어나지 않도록 조건을 넣어주어야 한다.
<전체 코드>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
#include<iostream>
#include<string>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
queue<pair<int,int>> q;
int T,m,n,k;
int cnt;
int map[50][50];
int his[50][50];
int my[4] = {-1,+1,0,0}; //위 아래 왼 오
int mx[4] = {0,0,-1,+1};
void BFS(int y, int x){
his[y][x] = 1; // 방문 표시
q.push(make_pair(y, x)); //삽입
while(!q.empty()){
pair<int, int> tem = q.front();
q.pop();
for(int i = 0; i<4; i++){
if(tem.first+my[i] >=0 && tem.first+my[i]<n && tem.second+mx[i] >=0 && tem.second+mx[i]<m){
if(map[tem.first+my[i]][tem.second+mx[i]] == 1 && his[tem.first+my[i]][tem.second+mx[i]] == 0){
his[tem.first+my[i]][tem.second+mx[i]] = 1; // 방문
pair<int, int> _tem = make_pair(tem.first+my[i], tem.second+mx[i]);
q.push(_tem);
}
}
}
}
}
int main(){
cin>>T;
for(int t = 0; t<T; t++){
memset(map, 0, sizeof(map));
memset(his,0,sizeof(his));
cnt = 0;
cin>>m>>n>>k;
for(int i = 0; i<k; i++){
int x,y;
cin>>x>>y;
map[y][x] = 1;
}
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++){
if(map[i][j] == 1 && his[i][j] == 0){
BFS(i,j);
cnt++;
}
}
}
cout<<cnt<<endl;
}
}
|
cs |
'BOJ' 카테고리의 다른 글
BOJ 3986번 : 좋은 단어 (0) | 2022.03.18 |
---|---|
BOJ 16120번 : PPAP (0) | 2022.03.18 |
BOJ 15651번 : N과 M(3) (0) | 2020.11.16 |
BOJ 15650번 : N과 M(2) (0) | 2020.11.16 |
BOJ 15649번 : N과 M(1) (0) | 2020.11.16 |
Comments