문제
https://www.acmicpc.net/problem/2636
2636번: 치즈
아래 <그림 1>과 같이 정사각형 칸들로 이루어진 사각형 모양의 판이 있고, 그 위에 얇은 치즈(회색으로 표시된 부분)가 놓여 있다. 판의 가장자리(<그림 1>에서 네모 칸에 X친 부분)에는 치즈가 놓
www.acmicpc.net
해설
탐색 -> 1을 만날시 해당 값을 변경후 탐색을 멈추도록 구현
bfs / dfs 둘다 가능 => dfs선택 (bfs선택시 메모리 초과 조심)
코드
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
|
#include <bits/stdc++.h>
using namespace std;
int xx, yy, mp[104][104], visited[104][104], ret1, ret2;
int dx[] = {0, 1, 0, -1};
int dy[] = {-1, 0, 1, 0};
queue<pair<int, int>> q;
int countSize()
{
int countSize = 0;
for (int i = 0; i < yy; i++)
{
for (int j = 0; j < xx; j++)
{
if (mp[i][j] == 1)
countSize++;
}
}
return countSize;
}
void dfs(int y, int x)
{
visited[y][x] = 1;
for (int i = 0; i < 4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || ny < 0 || nx >= xx || ny >= yy || visited[ny][nx] == 1)
continue;
else if (mp[ny][nx] == 1)
{
mp[ny][nx] = 0;
visited[ny][nx] = 1;
}
else if (mp[ny][nx] == 0)
dfs(ny, nx);
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> yy >> xx;
for (int i = 0; i < yy; i++)
{
for (int j = 0; j < xx; j++)
{
cin >> mp[i][j];
}
}
while (true)
{
int cnt = countSize();
if (cnt == 0)
{
break;
}
else
ret2 = cnt;
fill(&visited[0][0], &visited[0][0] + 104 * 104, 0);
dfs(0, 0);
ret1++;
}
cout << ret1 << "\n"
<< ret2;
}
|
cs |
'백준 알고리즘(C++)' 카테고리의 다른 글
백준 1325번 효율적인 해킹 ( C++ ) (0) | 2024.03.28 |
---|---|
백준 1068번 트리 ( C++ ) (0) | 2024.03.28 |
백준 14502번 연구소 ( C++ ) (0) | 2024.03.26 |
백준 4949번 균형잡힌 세상 ( C++ ) (0) | 2024.03.24 |
백준 9012번 괄호 ( C++ ) (0) | 2024.03.23 |