[백준 알고리즘]/[C++]
14716번 현수막 | BFS, DFS | 백준 14716 C++ 코드
말하는펭귄
2021. 2. 24. 01:46
728x90
반응형
이번 포스팅은 백준 14716번 현수막입니다.
아래 url를 클릭하시면 백준 사이트에서 문제를 볼 수 있습니다.
14716번: 현수막
혁진이의 생각대로 프로그램을 구현했을 때, 현수막에서 글자의 개수가 몇 개인지 출력하여라.
www.acmicpc.net
기본 알고리즘
BFS 너비 우선 탐색
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
|
//백준14716 현수막
#include <iostream>
#include <queue>
using namespace std;
int M, N;
const int MAX = 251;
int map[MAX][MAX];
bool visited[MAX][MAX];
int dy[] = { 0,0,-1,1,-1,-1,1,1 };
int dx[] = { 1,-1,0,0,-1,1,-1,1 };
queue<pair<int, int>> q;
void BFS(int y, int x) {
visited[y][x] = true;
q.push(make_pair(y, x));
while (!q.empty()) {
y = q.front().first;
x = q.front().second;
q.pop();
for (int i = 0; i < 8; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny<0 || nx<0 || ny>=M || nx>=N)
continue;
if (map[ny][nx] == 1 && visited[ny][nx] == 0) {
visited[ny][nx] = true;
q.push(make_pair(ny, nx));
}
}
}
}
int main() {
cin >> M >> N; //행 열
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
cin >> map[i][j];
}
}
int ans = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1 && visited[i][j] == 0) {
BFS(i, j);
ans++;
}
}
}
cout << ans;
}
|
cs |
DFS 깊이 우선 탐색
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
|
//백준14716 현수막
#include <iostream>
using namespace std;
int M, N;
const int MAX = 251;
int map[MAX][MAX];
bool visited[MAX][MAX];
int dy[] = { 0,0,-1,1,-1,-1,1,1 };
int dx[] = { 1,-1,0,0,-1,1,-1,1 };
void DFS(int y, int x) {
visited[y][x] = true;
for (int i = 0; i < 8; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || ny >= M || nx >= N)
continue;
if (map[ny][nx] == 1 && visited[ny][nx] == 0) {
visited[ny][nx] = 1;
DFS(ny, nx);
}
}
}
int main() {
cin >> M >> N; //행 열
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
cin >> map[i][j];
}
}
int ans = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1 && visited[i][j] == 0) {
DFS(i, j);
ans++;
}
}
}
cout << ans;
}
|
cs |
728x90
반응형