코딩공작소
[백준]구슬탈출2(두번째) 본문
https://www.acmicpc.net/problem/13460
13460번: 구슬 탈출 2
첫 번째 줄에는 보드의 세로, 가로 크기를 의미하는 두 정수 N, M (3 ≤ N, M ≤ 10)이 주어진다. 다음 N개의 줄에 보드의 모양을 나타내는 길이 M의 문자열이 주어진다. 이 문자열은 '.', '#', 'O', 'R', 'B' 로 이루어져 있다. '.'은 빈 칸을 의미하고, '#'은 공이 이동할 수 없는 장애물 또는 벽을 의미하며, 'O'는 구멍의 위치를 의미한다. 'R'은 빨간 구슬의 위치, 'B'는 파란 구슬의 위치이다. 입력되는 모든 보드
www.acmicpc.net
역시나 어려운 문제... 최단거리 --> bfs, 상화좌우로 이동 --> 시뮬로 쭉 끝까지 이동
isV를 4차원으로 생각 , 여러가지 예외상황과 겹치는 경우 많이 이동한 구슬이 전단계로 Back.. 등등
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 | #include <iostream> #include <queue> #include <cstring> using namespace std; struct INFO { int rr, rc, br, bc; INFO() {}; INFO(int rr, int rc, int br, int bc) :rr(rr), rc(rc), br(br), bc(bc) {}; }; int N, M; char map[10][10]; bool isV[10][10][10][10]; //R_r,R_c,B_r,B_c int Red_r, Red_c, Blue_r, Blue_c; int R, C; int dr[] = { 1,-1,0,0 }, dc[] = { 0,0,1,-1 }; int ans = 1e9; queue<INFO> q; void move(int &r, int &c, int dir) { while (1) { r += dr[dir]; c += dc[dir]; if (map[r][c] == '#') { r -= dr[dir]; c -= dc[dir]; break; } if (map[r][c] == 'O') break; } } void solve() { int cnt = 1; while (!q.empty()) { int qlen = q.size(); while (qlen--) { //사이즈만큼 실행 --> 단계별로 실행. int nrr = q.front().rr, nrc = q.front().rc; int nbr = q.front().br, nbc = q.front().bc; q.pop(); for (int i = 0; i < 4; i++) { int nr = nrr, nc = nrc, nr1 = nbr, nc1 = nbc; move(nr, nc, i); move(nr1, nc1, i); if (map[nr1][nc1] == 'O') continue; //파란구슬이 빠지는 경우 if (map[nr][nc] == 'O') { ans = cnt; return; } //빨간구슬만 빠지는 경우 if (nr == nr1 && nc == nc1) { //겹치는 경우 if (abs(nr - nrr) + abs(nc - nrc) < abs(nr1 - nbr) + abs(nc1 - nbc)) nr1 -= dr[i], nc1 -= dc[i]; else nr -= dr[i], nc -= dc[i]; } if (isV[nr][nc][nr1][nc1] == true) continue; isV[nr][nc][nr1][nc1] = true; q.push({ nr,nc,nr1,nc1 }); } } //queue end if (cnt >= 10) return; cnt++; } } int main() { cin >> N >> M; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> map[i][j]; if (map[i][j] == 'R') { Red_r = i; Red_c = j; } else if (map[i][j] == 'B') { Blue_r = i; Blue_c = j; } else if (map[i][j] == 'O') { R = i; C = j; } } } //queue 시작. q.push({ Red_r,Red_c,Blue_r,Blue_c }); isV[Red_r][Red_c][Blue_r][Blue_c] = true; solve(); printf("%d\n", ans == 1e9 ? -1 : ans); return 0; } | cs |
'알고리즘 > 그래프' 카테고리의 다른 글
[백준]연구소(두번째풂) (0) | 2019.08.20 |
---|---|
[SWEA]등산로조성 (0) | 2019.08.18 |
[백준]보물섬 (0) | 2019.08.16 |
[백준]꽃길 (0) | 2019.08.09 |
[백준]게임(미완성) (0) | 2019.08.09 |