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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
 
using namespace std;
vector<vector<int>> map(26vector<int>(260));
vector<vector<bool>> visit(26vector<bool>(26false));
int n;
int cnt = 0;
vector<int> houseCnt;  //houseCnt[cnt]로 접근. 1부터
 
void dfs(int row, int col) {
    visit[row][col] = true;
    ++houseCnt[cnt];  //cnt번째 단지의 집 갯수 늘리기
 
    if (row - 1 >= 1 && !visit[row - 1][col] && map[row - 1][col] == 1)
        dfs(row - 1, col); //위
 
    if (row + 1 <= n && !visit[row + 1][col] && map[row + 1][col] == 1)
        dfs(row + 1, col); //아래
 
    if (col - 1 >= 1 && !visit[row][col - 1&& map[row][col - 1== 1)
        dfs(row, col - 1); //왼쪽
 
    if (col + 1 <= n && !visit[row][col + 1&& map[row][col + 1== 1)
        dfs(row, col + 1); //오른쪽
}
 
int main() {
    houseCnt.push_back(0);  //index 1부터 시작하기 위해서 넣어놓기. 안쓰는 [0]
    scanf("%d"&n);
 
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            scanf("%1d"&map[i][j]);  //한자리씩 입력 받음
        }
    }
 
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (map[i][j] != 0 && !visit[i][j]) {
                houseCnt.push_back(0);
                ++cnt;  //단지의 갯수 늘리기
                dfs(i, j);
            }
        }
    }
 
    printf("%d\n", cnt);
    sort(houseCnt.begin(), houseCnt.end());  //오름차순 출력을 위해서
    for (int i = 1; i < houseCnt.size(); i++)
        printf("%d\n", houseCnt[i]);
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

dfs 아닌데 하다보니까 함수이름을 dfs로 지어버림..

 

 

'Baekjoon' 카테고리의 다른 글

[#2178] 미로탐색  (0) 2020.03.31
[#1012] 유기농 배추  (0) 2020.03.31
[#1260] DFS와 BFS  (0) 2020.03.31
[#11286] 절댓값 힙  (0) 2020.03.17
[#1927] 최소 힙  (0) 2020.03.17

+ Recent posts