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 | #include <stdio.h> #include <queue> #include <utility> #include <string.h> using namespace std; int arr[104][104] = { 0 }; int chk[104][104] = { 0 }; int chkMat[104][104] = { 0 }; int n, sum = 0; void isLink(int a, int b) { queue<pair<int, int>> q; q.push(make_pair(a, b)); int dx[4] = { 1,-1,0,0 }; int dy[4] = { 0,0,1,-1 }; while (!q.empty()) { int y = q.front().first; int x = q.front().second; q.pop(); chkMat[y][x] = -1; for (int i = 0; i < 4; i++) { int xx = x + dx[i]; int yy = y + dy[i]; if (xx <= 0 || xx > n || yy <= 0 || yy > n) continue; if (chkMat[yy][xx] != 1) continue; q.push(make_pair(yy, xx)); } } } void scoreChk() { memcpy(chkMat, chk, sizeof(chk)); int rst = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (chkMat[i][j] == 1) { isLink(i, j); rst++; } } } if (rst == 2) sum++; } void bridge(int cnt, int len) { if (cnt < len) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (chk[i][j] == 0) { chk[i][j] = 1; bridge(cnt + 1, len); chk[i][j] = 0; } } } } else { if (sum == 0) { scoreChk(); } } } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { scanf("%d", &arr[i][j]); chk[i][j] = arr[i][j]; } for (int i = 1; i <= 3; i++) { bridge(0, i); if (sum!=0) { printf("%d", i); break; } } } | cs |
'알고리즘 > DFS' 카테고리의 다른 글
2250 트리의 높이와 너비 (0) | 2020.01.22 |
---|---|
14502 연구실 (0) | 2020.01.17 |
4677 Oil Deposit (0) | 2020.01.14 |
2468 안전영역 (0) | 2020.01.14 |
2798 블랙잭 (0) | 2019.09.15 |