티스토리 뷰

Algorithm/BOJ

백준 2468번 C++

poopooreum 2023. 8. 7. 20:49
반응형
백준 2468번 안전 영역

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

2468번: 안전 영역

재난방재청에서는 많은 비가 내리는 장마철에 대비해서 다음과 같은 일을 계획하고 있다. 먼저 어떤 지역의 높이 정보를 파악한다. 그 다음에 그 지역에 많은 비가 내렸을 때 물에 잠기지 않는

www.acmicpc.net



정답 코드

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
 
int N;
const int MAX = 101;
int input[MAX][MAX];
int map[MAX][MAX];
bool visited[MAX][MAX];
int dy[] = { 0,0,-1,1 };
int dx[] = { -1,1,0,0 };
queue<pair<int, int>> q;
vector<int> v; 
int cnt; 
 
void BFS(int y, int x) {
    visited[y][x] = true;
    q.push(make_pair(y, x));
 
    while (!q.empty()) {
        y = q.front().first;
        x = q.front().second;
        q.pop();
 
        for (int i = 0; i < 4; i++) {
            int ny = y + dy[i];
            int nx = x + dx[i];
 
            if (ny < 0 || nx < 0 || ny >= N || nx >= N)
                continue;
            if (map[ny][nx] && !visited[ny][nx]) {
                visited[ny][nx] = true;
                q.push(make_pair(ny, nx));
            }
        }
    }
}
 
void reset() {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            map[i][j] = 0;
            visited[i][j] = 0;
        }
    }
    cnt = 0;
}
 
int main() {
    int maxHeight = -1;
    cin >> N;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cin >> input[i][j];
            if (input[i][j] > maxHeight) {
                maxHeight = input[i][j];
            }
        }
    }
 
    for (int h = 1; h <= maxHeight; h++) {

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (input[i][j] < h) {
                    map[i][j] = 0;
                }
                else {
                    map[i][j] = 1;
                }
            }
        }
 
       
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (map[i][j] && !visited[i][j]) {
                    BFS(i, j);
                    cnt++;
                }
            }
        }
        v.push_back(cnt);
        
        /*초기화*/
        reset();
    }
 
    sort(v.begin(), v.end()); 
    cout << v[v.size() - 1];  
}

문제 풀이

bfs를 이용해서 풀 수 있습니다. 문제 서론이 생각보다 길긴 하지만 의외로 단순합니다. 주어진 높이보다 높이가 낮은 곳들은 0으로 나머지 곳들은 1로 처리한 후
bfs를 돌리면 됩니다. 이때 시작하는 좌표들은 한 곳이 아니기 때문에 반복문을 돌리면서 찾을 때마다 bfs를 돌려주면 됩니다. 그리고 그때마다 count개수를 1개씩 더해주시면 됩니다.

반응형

'Algorithm > BOJ' 카테고리의 다른 글

백준 2480번 C++  (0) 2023.08.07
백준 2475번 C++  (0) 2023.08.07
백준 2448번 C++  (0) 2023.08.07
[C/C++] 백준 2447번 - 별 찍기10  (0) 2023.08.07
백준 2444번 C++  (0) 2023.08.06
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함