문제
접근
기본적인 BFS 문제이다.
- 1인 영역을 검출하는 단계
- 검출된 영역에서 BFS를 이용하여 연결된 1을 찾는 단계
로 이루어진다.
코드
- C++ 코드
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
#include<iostream>
#include<queue>
using namespace std;
int board[500][500];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
int maxSize = 0;
int n, m;
queue<pair<int, int>> q;
void bfs();
int main() {
cin >> n >> m;
int paintCnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> board[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (board[i][j] == 1) {
board[i][j] = 2;
q.push({ i, j });
bfs();
paintCnt++;
}
}
}
cout << paintCnt << endl;
cout << maxSize << endl;
return 0;
}
void bfs() {
int size = 1;
while (!q.empty()) {
pair<int, int> cur = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = cur.first + dx[i];
int ny = cur.second + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= m)
continue;
if (board[nx][ny] != 1)
continue;
board[nx][ny] = 2;
q.push({ nx,ny });
size++;
}
}
if (size > maxSize)
maxSize = size;
}
- 파이썬 코드
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
import sys
import queue
paintCnt = 0
maxSize = 0
n, m = map(int, input().split())
board = [list(map(int, input().split())) for i in range(n)]
dx = [0, 1, 0, -1]
dy = [-1, 0, 1, 0]
q = queue.Queue()
def bfs():
size = 1
while not q.empty():
cur = q.get()
for x, y in zip(dx, dy):
nx = cur[0] + x
ny = cur[1] + y
if nx < 0 or nx >= n or ny < 0 or ny >= m:
continue
if board[nx][ny] != 1:
continue
board[nx][ny] = 2
q.put([nx, ny])
size += 1
return size
for i in range(n):
for j in range(m):
if board[i][j] == 1:
board[i][j] = 2
q.put([i,j])
size = bfs()
if size > maxSize:
maxSize = size
paintCnt+=1
print(paintCnt)
print(maxSize)