티스토리 뷰

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;


}

'PS' 카테고리의 다른 글

[백준] 2294번 동전2 C++  (0) 2022.06.23
[백준] 14606번 피자(small)  (0) 2022.06.22
[백준] 1922번 네트워크 연결  (0) 2022.05.27
[백준] 1004번 어린왕자  (0) 2022.05.22
[백준] 2877번 4와 7 C++  (0) 2022.05.21
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/01   »
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
글 보관함