프로그래밍/알고리즘

BOJ 2636 · 치즈

반응형


알고리즘 분류 : BFS  


치즈가 완전히 녹을 때까지 걸리는 시간을 구하는 문제다. BOJ 2638번 '치즈'와 유사하다. 자세한 내용은 이전 문제 참조.


  • 치즈 칸(1)에 외부 공기(1)가 인접한다면, 치즈를 녹인다.
  • 치즈를 녹일 때마다, 녹인 개수를 저장한다.




C++ 소스코드


#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

struct cheese {
    int x, y;
};

int n, m, ans, piece;
int a[100][100];
bool check[100][100];
const int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};

void bfs() {
    memset(check, false, sizeof(check));
    queue<cheese> q;
    q.push({0, 0});
    check[0][0] = true;
    while (!q.empty()) {
        int x = q.front().x, y = q.front().y; q.pop();
        for (int i=0; i<4; i++) {
            int nx = x+dx[i], ny = y+dy[i];
            if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
            if (check[nx][ny]) continue;
            if (a[nx][ny] >= 1) {
                a[nx][ny] += 1;
                continue;
            }
            q.push({nx, ny});
            check[nx][ny] = true;
        }
    }
}

bool melt() {
    bool melted = false;
    int cnt = 0;
    for (int i=0; i<n; i++) {
        for (int j=0; j<m; j++) {
            if (a[i][j] >= 2) {
                a[i][j] = 0;
                melted = true;
                cnt += 1;
            }
        }
    }
    if (cnt) piece = cnt;
    return melted;
}

int main() {
    scanf("%d %d", &n, &m);
    for (int i=0; i<n; i++) {
        for (int j=0; j<m; j++) {
            scanf("%d", &a[i][j]);
        }
    }
    while (true) {
        bfs();
        if (melt()) ans++;
        else break;
    }
    printf("%d\n%d\n", ans, piece);
    return 0;
}




Python 3 소스코드


from collections import deque
from sys import stdin
input = stdin.readline

def bfs():
    q = deque()
    q.append((0, 0))
    check = [[False]*m for _ in range(n)]
    check[0][0] = True
    while q:
        x, y = q.popleft()
        for dx, dy in (-1,0), (1,0), (0,-1), (0,1):
            nx, ny = x+dx, y+dy
            if nx < 0 or nx >= n or ny < 0 or ny >= m:
                continue
            if not check[nx][ny]:
                if a[nx][ny] >= 1:
                    a[nx][ny] += 1
                else:
                    q.append((nx, ny))
                    check[nx][ny] = True

def melt():
    global piece
    melted, cnt = False, 0
    for i in range(n):
        for j in range(m):
            if a[i][j] >= 2:
                a[i][j] = 0
                melted = True
                cnt += 1
    if cnt:
        piece = cnt
    return melted


n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
ans, piece = 0, 0
while True:
    bfs()
    if melt():
        ans += 1
    else:
        break
print(ans)
print(piece)




참고



반응형