알고리즘 문제/BOJ
1726번 로봇
parkit
2019. 8. 5. 08:54
728x90
반응형
https://www.acmicpc.net/problem/1726
핵심은 rotation 배열이다.
rotation[a][b] = a번 상태에서 b번 상태로 회전하는데 횟수
또한, 문제 잘 읽자.
나는 최대 3까지 이동하는지 모르고,
끝까지 갈 수 있는 것으로 생각하여 구현했었다.
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 | #include <bits/stdc++.h> using namespace std; typedef struct info { int y, x, dir, Min; }info; int Map[101][101], r, c, sy, sx, ss, ey, ex, es; int dy[5] = { 0, 0, 0, 1, -1 }; int dx[5] = { 0, 1, -1, 0, 0 }; int rotation[5][5]; bool visit[101][101][5]; queue<info> q; int bfs() { visit[sy][sx][ss] = true; q.push({ sy, sx, ss, 0 }); while (!q.empty()) { int qSize = q.size(); while (qSize--) { int y = q.front().y, x = q.front().x, dir = q.front().dir, Min = q.front().Min; q.pop(); if (y == ey && x == ex && dir == es) return Min; for (int i = 1; i <= 3; i++) { int ny = y + dy[dir] * i; int nx = x + dx[dir] * i; // 범위 초과 또는 벽이면 어차피 더 이상 갈 수 없으므로, break if (ny <= 0 || ny > r || nx <= 0 || nx > c || Map[ny][nx]) break; // 이미 방문했던 곳이면, 그 다음 칸 여부를 확인 if (visit[ny][nx][dir]) continue;; visit[ny][nx][dir] = true; // 그냥 Min이 아니라, Min + 1 이다. 그 방향으로도 셈해야 한다. q.push({ ny, nx, dir, Min + 1 }); } for (int i = 1; i <= 4; i++) if (i != dir && !visit[y][x][i]) { visit[y][x][i] = true; q.push({ y, x, i, Min + rotation[dir][i] }); } } } } int main(void) { rotation[1][2] = rotation[2][1] = 2; rotation[3][4] = rotation[4][3] = 2; rotation[1][3] = rotation[3][1] = 1; rotation[1][4] = rotation[4][1] = 1; rotation[2][3] = rotation[3][2] = 1; rotation[2][4] = rotation[4][2] = 1; scanf("%d %d", &r, &c); for (int i = 1; i <= r; i++) for (int j = 1; j <= c; j++) scanf("%d", &Map[i][j]); scanf("%d %d %d %d %d %d", &sy, &sx, &ss, &ey, &ex, &es); printf("%d\n", bfs()); return 0; } | cs |
728x90
반응형