티스토리 뷰

728x90

문제 링크

www.acmicpc.net/problem/2636

 

2636번: 치즈

아래 <그림 1>과 같이 정사각형 칸들로 이루어진 사각형 모양의 판이 있고, 그 위에 얇은 치즈(회색으로 표시된 부분)가 놓여 있다. 판의 가장자리(<그림 1>에서 네모 칸에 X친 부분)에는 치즈가 놓

www.acmicpc.net

 

풀이

치즈 외부의 공기와 접촉하면 치즈가 녹아 없어지지만, 내부 공기와 접촉된 치즈에 대해선 처리하지 않아야합니다.

bfs를 돌리는데, 치즈를 주체로 돌리지 않고 (0, 0)의 공기를 시작점으로 하여 돌려줍시다.

 

 

정답 코드

#include <bits/stdc++.h>

#define ft first
#define sd second

using namespace std;
using pii = pair<int, int>;

int n, m;
int p[111][111];
bool chk[111][111];

bool isValid(int x, int y) {
    return 0 <= x && x < n && 0 <= y && y < m;
}

int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};

int bfs() {
    queue<pii> q, del;
    int cnt = 0;
    memset(chk, 0, sizeof(chk));

    chk[0][0] = true;
    q.emplace(0, 0);
    while (!q.empty()) {
        auto[x, y] = q.front();
        q.pop();
        for (int k = 0; k < 4; k++) {
            int nx = x + dx[k], ny = y + dy[k];
            if (!isValid(nx, ny) || chk[nx][ny]) continue;
            if (p[nx][ny]) {
                del.emplace(nx, ny);
                cnt++;
            } else {
                q.emplace(nx, ny);
            }
            chk[nx][ny] = true;
        }
    }

    while (!del.empty()) {
        auto[x, y] = del.front();
        del.pop();
        p[x][y] = 0;
    }

    return cnt;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> n >> m;
    pii ans;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> p[i][j];
            ans.sd += p[i][j];
        }
    }
    while (ans.sd > 0) {
        int c = bfs();
        ans.ft += 1;
        if (ans.sd - c == 0) break;
        ans.sd -= c;

    }
    cout << ans.ft << '\n' << ans.sd;
}
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함