Posts [BOJ 백준] 1926번 그림 / C++
Post
Cancel

[BOJ 백준] 1926번 그림 / C++


Contents



문제


문제를 보시려면 링크를 클릭해주세요.


풀이


BFS(너비 우선 탐색)로 풀었습니다.

그림을 찾을 때, 방문한 적이 없고 색칠이 된 부분을 시작점으로 찾아 상,하,좌,우 탐색을 해줍니다.

그림의 넓이큐에서 pop 하는 횟수로 알 수 있고, 그림의 개수새로운 색칠된 시작점을 찾은 기준으로 알 수 있습니다.


소스 코드


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 <utility>
#include <queue>

using namespace std;

int main(){
	
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	int arr[501][501];
	bool chk[501][501]; // 방문 여부 
	
	queue<pair<int,int> > Q;
	int n,m;

	cin >> n >> m;
	
	int dx[4] = {1,0,-1,0};
	int dy[4] = {0,1,0,-1};
	
	for(int i=0; i<n; i++){
		for(int j=0; j<m; j++){
			cin >> arr[i][j];	
		}		
	}
	
	int area = 0; // 그림의 넓이 
	int max = 0; 
	int num = 0; // 그림의 개수 
	
	for(int i=0; i<n; i++){
		for(int j=0; j<m; j++){
			
			if(chk[i][j] || arr[i][j]==0)
				continue;
				
			chk[i][j] = 1;
			Q.push({i,j});
			area = 0;
			num++;
			
			while(!Q.empty()){
				pair<int,int> cur = Q.front();
				Q.pop();
				
				area++;
				
				for(int dir=0; dir<4; dir++){
					int nx = cur.first + dx[dir];
					int ny = cur.second + dy[dir];
					
					if(nx < 0 || nx >= n || ny < 0 || ny >=m)
						continue;
						
					if(chk[nx][ny] || arr[nx][ny]==0)
						continue;
					
					chk[nx][ny]=1;
					Q.push({nx,ny});
				}
				
				if(max < area)
					max = area;
				
			}
		}
	}
	
	cout << num << "\n" << max;
	
	return 0; 

}



This post is licensed under CC BY 4.0 by the author.

[DB 데이터베이스] 정규화 (Normalization) 및 이상 (Anomaly)

[BOJ 백준] 2178번 미로 탐색 / C++

Comments powered by Disqus.