이 문제는 3개의 벽을 맵에 세우고 바이러스가 퍼졌을 때 안전 구역의 최대 갯수를 구하는 문제이다. 벽은 안전구역에 설치할 수 있고 무조건 3개를 설치한다.
문제 풀이 : 벽을 세울 수 있는 3곳을 모두 만들어 본 뒤 바이러스 지역에서 bfs 를 돌려 바이러스를 퍼뜨리고 그 후에 안전 구역의 갯수를 계산했다. 시간복잡도는 N과 M 이 최대 8이므로 (8 X 8)^3 이다. 여기에 bfs를 돌리므로 8 ^2을 곱하면 8^8 = 2^24 =1677216 이다.
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | #include <iostream> #include <vector> #include <queue> using namespace std; int dx[] = {-1,1,0,0}; int dy[] = {0,0,-1,1}; int N, M; vector <pair<int, int> > z; vector <pair<int, int> > v; int ans; void bfs(vector <vector <int> > &temp, int x, int y) { queue <pair <int, int> > q; q.push({ x,y }); while (!q.empty()) { int a = q.front().first; int b = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int nx = a + dx[i]; int ny = b + dy[i]; if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue; if (temp[nx][ny] == 2 || temp[nx][ny] == 1) continue; temp[nx][ny] = 2; q.push({ nx, ny }); } } } void solve(vector <vector <int> > &map, int cnt, int index) { if (cnt == 3) { vector <vector <int> > temp(map); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (temp[i][j] == 2) bfs(temp, i, j); } } int sum = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (temp[i][j] == 0) sum++; } } if (ans < sum) ans = sum; return; } for (int i = index; i < z.size(); i++) { map[z[i].first][z[i].second] = 1; solve(map, cnt + 1, i+1); map[z[i].first][z[i].second] = 0; } } int main() { cin >> N >> M; vector <vector <int> > map(N, vector<int>(M)); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> map[i][j]; if (map[i][j] == 0) z.push_back({ i,j }); } } ans = 0; solve(map,0,0); cout << ans << '\n'; return 0; } | cs |
반응형
'Computer Science > Algorithm' 카테고리의 다른 글
[Algorithm] 최소 공통 조상 LCA (Lowest Common Ancestor) (3) | 2019.01.13 |
---|---|
[Algorithm] 인덱스 트리(Indexed Tree) (0) | 2019.01.12 |
[BOJ 14503] 로봇 청소기 (0) | 2018.10.18 |
[BOJ 14890] 경사로 (0) | 2018.10.17 |
[BOJ 14889] 스타트와 링크 (0) | 2018.10.17 |