백준/DFS BFS

[백준 2667번 / C++] 단지번호붙이기

배발자 2022. 1. 24.
반응형

  • bfs, dfs 자신있는 것으로 해보자. 
  • main문에서 함수 호출할 때 증가하는 cnt는 영역을 표현. 
  • 함수에서 또 함수를 호출할 때 증가하는 cnt는 영역안의 넓이를 표현. 
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std; 
int n; 
int dx[4] = { 0,0,1,-1 }; 
int dy[4] = { 1,-1,0,0 }; 
int map[25][25]; 
int visited[25][25]; 
int cnt1; 
void dfs(int y, int x) {
	cnt1++;
	for (int i = 0; i < 4; i++) {
		int nx = x + dx[i]; 
		int ny = y + dy[i]; 
		if (nx < 0 || nx >= n || ny < 0 || ny >= n)continue; 
		if (map[ny][nx] == 0 || visited[ny][nx] == 1)continue; 
		visited[ny][nx] = 1; 
		dfs(ny, nx); 
	}
	return; 
}
int main() {
	cin >> n; 
	for (int i = 0; i < n; i++) {
		string s; cin >> s; 
		for (int j = 0; j < n; j++) {
			map[i][j] = s[j]-'0'; 
		}
	}
	int cnt = 0; 
	vector <int> v; 
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (map[i][j] && !visited[i][j]) {
				visited[i][j] = 1;
				dfs(i, j); 
				
				v.push_back(cnt1); 
				cnt1 = 0; 		
				cnt++; 
			}
		}
	}
	cout << cnt << "\n"; 
	sort(v.begin(), v.end()); 
	for (int i = 0; i < v.size(); i++) {
		cout << v[i] << endl; 
	}
}

 

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

 

반응형

'백준 > DFS BFS' 카테고리의 다른 글

[백준 12851번 / C++] 숨바꼭질 2  (0) 2022.02.10
[백준 2636번 / C++] 치즈  (0) 2022.01.27
[백준 10026번 / C++] 적록색약  (0) 2022.01.24
[백준 1260번 / C++] DFS와 BFS  (0) 2022.01.20
[백준 7576 / C++] 토마토  (0) 2022.01.20

댓글