[백준 알고리즘]/[C++]
1926번 그림 | BFS, DFS | Baekjoon BOJ 백준 1926 C++ 코드
말하는펭귄
2021. 2. 11. 00:28
728x90
반응형
이번 포스팅은 백준 1926번 그림입니다.
아래 url를 클릭하시면 백준 사이트에서 문제를 볼 수 있습니다.
1926번: 그림
어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int n, m;
const int MAX = 501;
int map[MAX][MAX] = { 0, };
bool visited[MAX][MAX] = { 0, };
int dy[] = { 0,0,-1,1 };
int dx[] = { 1,-1,0,0 };
queue<pair<int,int>> q; //BFS 사용 큐
vector<int> v; //그림 개수 저장 벡터
int s = 1; //그림 넓이
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 < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || ny >= n || nx >= m)
continue;
if (map[ny][nx] == 1 && visited[ny][nx] == 0) {
visited[ny][nx] = true;
s++;
q.push(make_pair(ny, nx));
}
}
}
}
bool compare(int i, int j) {
return i > j;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
}
}
int cnt = 0; //영역 개수
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == 1 && visited[i][j] == 0) {
BFS(i, j);
v.push_back(s);
cnt++;
s = 1;
}
}
}
sort(v.begin(), v.end(), compare); //벡터 오름차순 정렬
cout << cnt << endl;
if (cnt == 0) {
cout << 0 << endl;
}
else {
cout << v[0] << endl;
}
}
|
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n, m;
const int MAX = 501;
int map[MAX][MAX] = { 0, };
bool visited[MAX][MAX] = { 0, };
int dy[] = { 0,0,-1,1 };
int dx[] = { 1,-1,0,0 };
vector<int> v; //그림 개수 저장 벡터
int s = 1; //그림 넓이
void DFS(int y, int x) {
visited[y][x] = true;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || ny >= n || nx >= m)
continue;
if (map[ny][nx] == 1 && visited[ny][nx] == 0) {
visited[ny][nx] = true;
s++;
DFS(ny, nx);
}
}
}
bool compare(int i, int j) {
return i > j;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
}
}
int cnt = 0; //영역 개수
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == 1&&visited[i][j]==0) {
DFS(i, j);
v.push_back(s);
cnt++;
s = 1;
}
}
}
sort(v.begin(), v.end(), compare); //벡터 오름차순 정렬
cout << cnt << endl;
if (cnt == 0) {
cout << 0 << endl;
}
else {
cout << v[0] << endl;
}
}
|
cs |
728x90
반응형