해당 문제는 BFS를 사용하여 풀었습니다.
이중 포문을 n과 m만큼 돌려서 이미 방문했거나 그림 조각이 없다면 continue를 시키고
방문하지 않고 그림조각이 존재한다면 queue에 새로운 그림조각 위치를 넣었습니다.
BFS로 근접한 그림조각? 이 있다면 count++ 시키고 가장 큰 값을 구합니다.
전체 그림을 구하는 방법은 이중 포문에서 새로운 그림 조각이 나타날때 증감을 시켜 구할 수 있습니다.
#include <bits/stdc++.h>
using namespace std;
int board[501][501] = {0,};
int vis[501][501] = {0,};
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int n, m;
int maxs = 0;
int mins = 0;
int c = 0;
int main() {
cin >> n >> m;
queue<pair<int,int>> Q;
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(vis[i][j] == 1 || board[i][j] != 1) {
continue;
}
Q.push({i,j});
vis[i][j] = 1;
mins++;
c = 0;
while(!Q.empty()){
pair<int,int> cur = Q.front(); Q.pop();
for(int k = 0; k < 4; k++) {
int nx = cur.first + dx[k];
int ny = cur.second + dy[k];
if((nx < 0 || nx >= n) || (ny < 0 || ny >= m)) continue;
if((vis[nx][ny] == 1) || (board[nx][ny] != 1)) continue;
Q.push({nx,ny});
vis[nx][ny]= 1;
}
c++;
}
if(c > maxs) {
maxs = c;
}
}
}
cout << mins << endl << maxs;
}
'개발 > 알고리즘' 카테고리의 다른 글
BFS 백준-2178 미로탐색 (실버 1) (0) | 2024.04.21 |
---|---|
2024-04-20 앳코더 (A,B,C) (0) | 2024.04.21 |
백준-6189 (골드 5) 옥상 정원 꾸미기 STACK (2) | 2024.04.18 |
백준 2775 - 부녀회장이 될테야 (브론즈 1) (0) | 2024.04.04 |
알고리즘 백준 1로 만들기 - 1463 (0) | 2024.03.18 |