이중 포문을 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;
}
백준 11062 카드 게임 혼내주기 (0) | 2021.08.01 |
---|---|
백준 10714 케이크 자르기 2 혼내주기 (0) | 2021.08.01 |
백준 1107 리모컨 혼내주기 (0) | 2021.08.01 |
백준 7662 이중 우선순위 큐 혼내주기 (0) | 2021.08.01 |
백준 11049 행렬 곱셈 순서 혼내주기 (0) | 2021.08.01 |
댓글 영역