상세 컨텐츠

본문 제목

백준 14502 연구소 혼내주기

혼내주기

by lazz 2021. 8. 1. 22:32

본문

반응형

이중 포문을 nm이 아니라 nn으로 돌다가 오래 헤맸다...

 

벽을 놓는 dfs를 돌릴 때 매번 0,0에서 시작하지 않고 다음 지점부터 시작하면 시간이 많이 단축된다.

 

요종도

 

#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(0), cin.tie(0)
using namespace std;

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

queue<pair<int, int> > viruses;
bool visited[8][8];
int arr[8][8];
int n, m, ans = 0, walls = 0;

void input() {
    fastio;
    cin >> n >> m;
    for(int i = 0; i < n; ++i) {
        for(int j = 0; j < m; ++j) {
            cin >> arr[i][j];
            if(arr[i][j] == 2) {
                visited[i][j] = true;
                viruses.push({i, j});
            }
            else if(arr[i][j] == 1)
                walls++;
        }
    }
}

void bfs() {
    memset(visited, false, sizeof(visited));
    queue<pair<int, int> > q(viruses);
    int cnt = n*m -3 -walls -q.size();
    
    while(!q.empty()) {
        auto [x, y] = q.front(); 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(visited[nx][ny] || arr[nx][ny] != 0) continue;

            visited[nx][ny] = true;
            q.push({nx, ny});
            cnt--;
        }
    }
    ans = max(ans, cnt);
}

void dfs(int x, int y, int cnt) {
    if(cnt == 0) {
        bfs();
        return ;
    }

    for(int i = x; i < n; ++i) {
        int start = 0;
        if(i == x) start = y;
        for(int j = start; j < m; ++j) {
            if(arr[i][j] != 0) continue;

            arr[i][j] = 3;
            if(j == m-1) dfs(i+1, 0, cnt-1);
            else dfs(i, j+1, cnt-1);
            arr[i][j] = 0;
        }
    }
}

int main() {
    input();
    dfs(0, 0, 3);
    cout << ans;
}
반응형

관련글 더보기

댓글 영역