14502번 - 연구소
17년 상반기 삼성 기출문제.
그때는 손도 못댔었다..
로직은 dfs 를 이용해서 벽 3개를 세운다(이때, 벽 3개 세우는거 중복을 막기 위해 인자를 추가로 넘겨준다)
벽 3개를 세운 이후에는 bfs를 이용해서 바이러스를 퍼뜨린다.
그리고 청정지역의 갯수를 세주면서, 최대값을 출력해주면 된다.
<정답 코드>
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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | #include<iostream> #include<queue> #include<string.h> using namespace std; int dx[4] = { 0,0,1,-1 }; int dy[4] = { 1,-1,0,0 }; int n, m; int map[9][9]; bool check[9][9]; int ans; void makewall(int k,int bx,int by) { if (k == 3) { memset(check, false, sizeof(check)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 2 && !check[i][j]) { queue<pair<int, int>> q; check[i][j] = true; q.push({ i,j }); while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int d = 0; d < 4; d++) { int nx = x + dx[d]; int ny = y + dy[d]; if (nx >= 0 && ny >= 0 && nx < n && ny < m && !check[nx][ny] && map[nx][ny] == 0) { check[nx][ny] = true; q.push({ nx,ny }); } } } } } } int cnt = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == 0 && !check[i][j]) { cnt++; } } } ans = cnt > ans ? cnt : ans; return; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if ((i == bx && j > by) || i>bx) { if (map[i][j] == 0) { map[i][j] = 1; makewall(k + 1, i, j); map[i][j] = 0; } } } } } int main() { //freopen("input.txt", "r", stdin); ios::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> map[i][j]; } } makewall(0,-1,-1); cout << ans << "\n"; return 0; } | cs |
반응형