PS
[백준] 1926번 그림 C++
Eastplanet
2022. 6. 21. 19:27
문제 출처: https://www.acmicpc.net/problem/1926
1926번: 그림
어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로
www.acmicpc.net
배열을 반복문을 돌며 검사하다가 1이 나오면 그림의 개수를 증가시키고 BFS를 돌려 이어진 1을 0으로 바꾸면서 그림의 크기를 검사하여 max값을 갱신해준다.
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
typedef pair<int, int>P;
int movepos[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
int n, m;
int arr[501][501];
bool canMove(int x, int y) {
if (x < 0 || x >= m)return false;
if (y < 0 || y >= n)return false;
return true;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> arr[i][j];
}
}
int max = 0;
int count = 0;
queue<P> q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] == 1) {
count++;
q.push(P(i, j));
arr[i][j] = 0;
int sum = 1;
while (!q.empty()) {
P curr = q.front(); q.pop();
int x = curr.second;
int y = curr.first;
for (int z = 0; z < 4; z++) {
int gox = x + movepos[z][0];
int goy = y + movepos[z][1];
if (canMove(gox, goy)) {
if (arr[goy][gox] == 1) {
arr[goy][gox] = 0;
sum++;
q.push(P(goy, gox));
}
}
}
}
if (sum > max) { max = sum; }
}
}
}
cout << count<<'\n';
cout << max;
}