안선생의 개발 블로그
C++ 1012 유기농 배추 본문
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
#include <iostream>
#include <vector>
#include<queue>
#include<algorithm>
using namespace std;
int g[51][51] = {};
bool visit[51][51] = {};
int n,m,k;
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
void dfs(int x, int y)
{
visit[x][y] = 1;
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 0 || xx > n || yy < 0 || yy > m || !g[xx][yy])
continue;
if (!visit[xx][yy] && g[xx][yy])
{
dfs(xx, yy);
}
}
}
void bfs(int x,int y)
{
queue<pair<int,int>> a;
a.push({ x,y });
while (!a.empty())
{
int xx = a.front().first;
int yy = a.front().second;
a.pop();
for (int i = 0; i <4; i++)
{
int x1 = xx + dx[i];
int y1 = yy + dy[i];
if (x1 < 0 || x1 > n || y1 < 0 || y1 > m|| !g[x1][y1])
continue;
if(!visit[x1][y1] && g[x1][y1])
{
a.push({ x1,y1 });
visit[x1][y1] = 1;
}
}
}
}
void reset()
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
g[i][j] = 0;
visit[i][j] = 0;
}
}
}
int main(void)
{
int input; cin >> input;
int result = 0;
while (input--)
{
cin >> n >> m >> k;
for (int i = 0; i < k; i++)
{
int a, b; cin >> a >> b;
g[a][b] = 1;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (!visit[i][j] && g[i][j])
{
dfs(i, j);
result++;
}
}
}
cout << result << "\n";
result = 0;
reset();
}
return 0;
}
|
cs |
https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에
www.acmicpc.net
'백준' 카테고리의 다른 글
C++ 10026 적록색약 (0) | 2023.02.17 |
---|---|
C++ 섬의 개수 (0) | 2023.02.17 |
C++ 2178 미로 탐색 (0) | 2023.02.16 |
C++ 24445 알고리즘 수업 - 너비 우선 탐색 2 (0) | 2023.02.16 |
C++ 24444 알고리즘 수업 - 너비 우선 탐색 1 (0) | 2023.02.16 |