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 | #include <stdio.h> #include <string.h> using namespace std; int width; int place[30][30]; int flag[30][30]; int desert[105]; int dx[5] = { 0, -1, 1, 1, -1 }; int dy[5] = { 0, 1, 1, -1, -1 }; int rst_max; void dfs(int y, int x, int dir); // 1:좌하 2:우하 3:우상 4:좌상 void print_flag(); int main() { int test; scanf("%d", &test); for (int t = 1; t <= test; t++) { scanf("%d", &width); memset(place, 0, sizeof(place)); memset(flag, 0, sizeof(flag)); memset(desert, 0, sizeof(desert)); rst_max = -1; for (int i = 1; i <= width; i++) for (int j = 1; j <= width; j++) scanf("%d", &place[i][j]); for (int i = 1; i <= width; i++) for (int j = 1; j <= width; j++) { flag[i][j] = -1; int d = place[i][j]; desert[d] = 1; dfs(i, j, 0); flag[i][j] = 0; desert[d] = 0; } printf("#%d %d\n", t, rst_max); } } // 1:좌하 2:우하 3:우상 4:좌상 void dfs(int y, int x, int dir) { if (y > width || y <= 0 || x > width || x <= 0) return; for (int i = 4; i >= 1; i--) { // 처음 시작일때 if (dir == 0) if ((i == 2) ||(i == 3) || (i == 4)) continue; // 좌하 일때 if (dir == 1) if ((i == 3) || (i == 4)) continue; // 우하 일때 if (dir == 2) if ((i == 1) || (i == 4)) continue; // 우상 일때 if (dir == 3) if ((i == 1) || (i == 2)) continue; // 좌상 일때 if (dir == 4) if ((i == 1) || (i == 2) || (i == 3)) continue; int xx = x + dx[i]; int yy = y + dy[i]; // 출발 지점에 도착했을 경우, 멈춘다 if (flag[yy][xx] == -1) { int total_v = 0; for (int i = 1; i <= 101; i++) if (desert[i] != 0) total_v += 1; if (total_v > rst_max) rst_max = total_v; return; } if (flag[yy][xx] == 1) continue; // 출발 지점이 아닐경우, 그대로 계속 dfs 를 진행한다 int d = place[yy][xx]; if (desert[d] == 0) { flag[yy][xx] = 1; desert[d] = 1; dfs(yy, xx, i); desert[d] = 0; flag[yy][xx] = 0; } } } | cs |
1시간정도 걸렸다
dfs 를 활용하는 문제였다
dfs 1개만 사용하면 되는 문제여서, 그 전 문제들보다는 쉬운 편이었다
'삼성 코팅테스트 준비 > 모의 역량 테스트 문제' 카테고리의 다른 글
1953 탈주범 검거 (0) | 2020.03.04 |
---|---|
2477 차량 정비소 (0) | 2020.03.04 |
2115 벌꿀채취 (0) | 2020.03.03 |
4012 요리사 (0) | 2020.03.03 |
시간초과) 5653 줄기세포 배양 (0) | 2020.03.03 |