반응형
https://www.acmicpc.net/problem/14923
14923번: 미로 탈출
홍익이는 사악한 마법사의 꾐에 속아 N x M 미로 (Hx, Hy) 위치에 떨어졌다. 다행히도 홍익이는 마법사가 만든 미로의 탈출 위치(Ex, Ey)를 알고 있다. 하지만 미로에는 곳곳에 마법사가 설치한 벽이
www.acmicpc.net
[ 문제풀이 ]
1. visited [ 1001 ][ 1001 ][ 2 ] 배열을 만들어서 벽을 부순 여부와 방문 여부를 기록합니다.
2. bfs를 활용하여 벽을 부순 횟수와 움직인 횟수 등을 queue에 넣고, 현재 위치가 Ex, Ey라면 cnt를 출력합니다.
3. 도착할 수 없는 경우 -1을 출력합니다.
[ 소스코드 ]
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 | #include<iostream> #include<queue> using namespace std; int N, M; int Hx, Hy; int Ex, Ey; int dy[4] = { -1,1,0,0 }; int dx[4] = { 0,0,-1,1 }; int arr[1001][1001]; int visited[1001][1001][2]; struct pos { int x; int y; int wall; int cnt; }; int main() { scanf("%d %d", &N, &M); scanf("%d %d", &Hx, &Hy); scanf("%d %d", &Ex, &Ey); for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { scanf("%d", &arr[i][j]); } } queue<pos> q; q.push({ Hx,Hy,0,0 }); visited[Hx][Hy][0] = 1; while (!q.empty()) { const int y = q.front().y; const int x = q.front().x; const int wall = q.front().wall; const int cnt = q.front().cnt; q.pop(); if (y == Ey && x == Ex) { printf("%d", cnt); return 0; } for (int i = 0; i < 4; i++) { const int yy = y + dy[i]; const int xx = x + dx[i]; if (xx > 0 && xx <= N && yy > 0 && yy <= M) { if (wall == 0 && arr[xx][yy] == 1) { if (visited[xx][yy][1] != 1) { visited[xx][yy][1] = 1; q.push({ xx,yy,1,cnt + 1 }); } } if (arr[xx][yy] == 0) { if (visited[xx][yy][wall] != 1) { visited[xx][yy][wall] = 1; q.push({ xx,yy,wall,cnt + 1 }); } } } } } printf("-1"); } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 16398번 - 행성 연결 (C++) (0) | 2023.01.28 |
---|---|
[ 백준 ] 17090번 - 미로 탈출하기 (C++) (0) | 2023.01.27 |
[ 백준 ] 5558번 - チーズ (Cheese) (C++) (0) | 2023.01.25 |
[ 백준 ] 3770번 - 대한민국 (C++) (0) | 2023.01.24 |
[ 백준 ] 9463번 - 순열 그래프 (C++) (0) | 2023.01.23 |