반응형

문제 출처 :


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



알고리즘 분석 :


문제 해결에 필요한 사항

1. BFS :: http://www.crocus.co.kr/521


간단한 bfs 문제이다.


함정이 있다면 배열의 크기 n이 최대 높이가 아니라는 것만 명심하면 된다.


3중 for문을 돌려도 100*100*100 = 1,000,000이고, bfs 또한 최대 100*100이나,


문제의 다양한 조건으로 인해 O(n^5)이라는 시간복잡도와는 다르게 20ms로 통과한다.  


소스 코드 : 


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
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <memory.h>
 
using namespace std;
 
typedef pair<intint> pii;
 
int map[101][101];
bool visit[101][101];
queue<pii> q;
 
int height;
int n;
 
void bfs(int i, int j)
{
    q.push(pii(i, j));
 
    while (!q.empty())
    {
        int y = q.front().first;
        int x = q.front().second;
 
        q.pop();
 
        if (visit[y][x])
            continue;
 
        visit[y][x] = true;
 
        // 범위를 넘지 않고, 방문하지 않았으며, height보다 크거나 같은 높이인 것
        if (y - >= && !visit[y - 1][x] && map[y - 1][x] >= height)
            q.push(pii(y - 1, x));
 
        if (y + < n && !visit[y + 1][x] && map[y + 1][x] >= height)
            q.push(pii(y + 1, x));
 
        if (x - >= && !visit[y][x - 1&& map[y][x - 1>= height)
            q.push(pii(y, x - 1));
 
        if (x + < n && !visit[y][x + 1&& map[y][x + 1>= height)
            q.push(pii(y, x + 1));
    }
}
 
int main()
{    
    scanf("%d"&n);
 
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            scanf("%d"&map[i][j]);
 
    int ans = 0;
 
    for(height = 1; height <= 100; height++)
    {
        // 초기화
        int cnt = 0;
 
        for (int i = 0; i < n; i++)
            memset(visit[i], 0sizeof(visit[i]));
 
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (!visit[i][j] && map[i][j] >= height)
                {
                    cnt++;
                    bfs(i, j);
                }
 
        // 침수 지역 최댓값
        ans = max(ans, cnt);
    }
 
    printf("%d", ans);
 
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus


반응형

'Applied > 알고리즘 문제풀이' 카테고리의 다른 글

[1759번] 암호 만들기  (2) 2017.03.28
[1162번] 도로포장  (7) 2017.03.28
[2302번] 극장 좌석  (0) 2017.03.27
[1504번] 특정한 최단 경로  (2) 2017.03.27
[7812번] 중앙 트리  (0) 2017.03.27