하다보니

1926번-그림 본문

알고리즘 풀이/백준

1926번-그림

claire 2022. 1. 26. 22:19
#include<bits/stdc++.h>
using namespace std;
#define X first
#define Y second


int board[502][502];
bool visit[502][502];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };

int main() {
	int n, m;
	queue<pair<int, int>> Q;
	vector<int> v;
	cin >> n >> m;
	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++) {
			int cnt = 0;
			if (board[i][j] == 1&&!visit[i][j]){
				Q.push({ i,j });
				visit[i][j] = 1;
				cnt += 1;
				while (!Q.empty()) {
					pair<int, int> cur = Q.front(); Q.pop();
					for (int p = 0; p < 4; p++) {
						int nx = cur.X + dx[p];
						int ny = cur.Y + dy[p];
						if (nx<0 || nx>n || ny < 0 || ny > m)continue;
						if (visit[nx][ny] || board[nx][ny] != 1)continue;
						visit[nx][ny] = 1;
						Q.push({ nx,ny });
						cnt += 1;
					}
				}
				v.push_back(cnt);
			}
			
		}
	}
	cout << v.size() << "\n";
	if(v.size()!=0)cout << *max_element(v.begin(),v.end());
	else cout << 0;

}

위에 벡터를 사용해서 저장하였지만 벡터를 사용하지 않고 코드를 완성할 수 있다. 

#include<bits/stdc++.h>
using namespace std;
#define X first
#define Y second


int board[502][502];
bool visit[502][502];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };

int main() {
	int n, m;
	int cnt=0; //도형 개수 
	int mx = 0;
	queue<pair<int, int>> Q;
	cin >> n >> m;
	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] == 0 || visit[i][j]) continue;		//빨리 리턴을 해주는 것이 좋다. 
			cnt += 1;
			Q.push({ i,j });
			visit[i][j] = 1;
			int area = 0;
			while (!Q.empty()) {
				area++;
				pair<int, int> cur = Q.front(); Q.pop();
				for (int p = 0; p < 4; p++) {
					int nx = cur.X + dx[p];
					int ny = cur.Y + dy[p];
					if (nx<0 || nx>=n || ny < 0 || ny >= m)continue;
					if (visit[nx][ny] || board[nx][ny] != 1)continue;
					visit[nx][ny] = 1;
					Q.push({ nx,ny });
				}
			}
			mx=max(mx, area);
		}
	}
	cout << cnt << "\n" << mx;

}

'알고리즘 풀이 > 백준' 카테고리의 다른 글

7576번-토마토  (0) 2022.01.29
2178번-미로탐색  (0) 2022.01.29
1021번-회전하는 큐  (0) 2022.01.23
10866번-덱  (0) 2022.01.23
2164번-카드2  (0) 2022.01.23