반응형

문제출처

https://www.acmicpc.net/problem/2667


DFS로 풀이한 문제 따로 visit배열을 사용하지 않고 dfs를 호출할 때 이미 방문한 곳은 값을 0으로 할당합니다. 때문에 map이 1인 경우만 탐색하면 되며 한개의 단지를 구한 후 dfs가 재호출될때 기존의 단지는 map상에 0이므로 재방문을 하지 않습니다. 


소스코드

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
//  main.cpp
//  BOJ_2667
//
//  Created by sw on 31/12/2018.
//  Copyright © 2018 sw. All rights reserved.
//
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#define MAX 25
 
using namespace std;
 
int n, cnt;
vector<int> section;
int map[MAX][MAX];
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
 
void init() {
    scanf("%d"&n);
    for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
        {
            int tmp;
            scanf("%1d"&tmp);
            map[i][j]=tmp;
        }
}
 
void dfs(int x, int y) {
    map[x][y]=0;
    cnt++;
    
    for(int i=0; i<4; i++)
    {
        int nx=x+dx[i];
        int ny=y+dy[i];
        
        if(nx>=0 && ny>=0 && nx<&& ny<&& map[nx][ny])
            dfs(nx, ny);
    }
}
 
int main(int argc, const char * argv[]) {
    init();
    
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            if(map[i][j])
            {
                cnt=0;
                dfs(i, j);
                section.push_back(cnt);
            }
        }
    }
    
    int len = section.size();
    printf("%d\n", len);
    
    sort(section.begin(), section.end());
    for(int i=0; i<len; i++)
        printf("%d\n", section.at(i));
    
    return 0;
}
 
cs



반응형

'Algorithm' 카테고리의 다른 글

[프로그래머스 43162] 네트워크  (0) 2019.01.01
[BOJ 6603] 로또  (0) 2018.12.31
[Programmers 43165] 타겟넘버  (0) 2018.12.31
[BOJ 2644] 촌수계산  (0) 2018.12.31
[BOJ 2606] 바이러스  (0) 2018.12.28

+ Recent posts