14923 미로탈출
2019. 3. 28. 23:39ㆍ알고리즘/백준
홍익대학교 기출문제로 최소를 구하는 전형적인 bfs 문제다.
벽을 부수는 경우의 수가 있다는 점에서 case를 두 개로 분리한다는 주의점이 있다.
문제: https://www.acmicpc.net/problem/14923
https://github.com/surinoel/algorithm/blob/master/14923.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <queue> | |
#include <tuple> | |
#include <cstring> | |
#include <iostream> | |
#include <algorithm> | |
using namespace std; | |
int mat[1000][1000]; | |
int dist[1000][1000][2]; | |
int dx[4] = { 1, -1, 0, 0 }; | |
int dy[4] = { 0, 0, 1, -1 }; | |
int main(void) { | |
ios_base::sync_with_stdio(false); | |
cin.tie(nullptr); | |
int n, m; | |
cin >> n >> m; | |
int sx, sy, ex, ey; | |
cin >> sx >> sy >> ex >> ey; | |
sx -= 1; | |
sy -= 1; | |
ex -= 1; | |
ey -= 1; | |
for (int i = 0; i < n; i++) { | |
for (int j = 0; j < m; j++) { | |
cin >> mat[i][j]; | |
} | |
} | |
memset(dist, -1, sizeof(dist)); | |
queue<tuple<int, int, int>> q; | |
q.push(make_tuple(sx, sy, 0)); | |
dist[sx][sy][0] = 0; | |
while (!q.empty()) { | |
int x, y, z; | |
tie(x, y, z) = q.front(); | |
q.pop(); | |
for (int k = 0; k < 4; k++) { | |
int tx = x + dx[k]; | |
int ty = y + dy[k]; | |
if (tx < 0 || ty < 0 || tx > n - 1 || ty > m - 1) continue; | |
if (mat[tx][ty] == 0 && dist[tx][ty][z] == -1) { | |
dist[tx][ty][z] = dist[x][y][z] + 1; | |
q.push(make_tuple(tx, ty, z)); | |
} | |
else if (mat[tx][ty] == 1 && z == 0) { | |
dist[tx][ty][z + 1] = dist[x][y][z] + 1; | |
q.push(make_tuple(tx, ty, z + 1)); | |
} | |
} | |
} | |
if (dist[ex][ey][0] == -1 && dist[ex][ey][1] == -1) { | |
cout << "-1\n"; | |
return 0; | |
} | |
if (dist[ex][ey][0] == -1) { | |
cout << dist[ex][ey][1] << '\n'; | |
} | |
else if (dist[ex][ey][1] == -1) { | |
cout << dist[ex][ey][0] << '\n'; | |
} | |
else { | |
cout << min(dist[ex][ey][0], dist[ex][ey][1]) << '\n'; | |
} | |
return 0; | |
} |
'알고리즘 > 백준' 카테고리의 다른 글
11048 이동하기 (0) | 2019.03.29 |
---|---|
(카카오) 15954 인형들 (0) | 2019.03.29 |
(카카오) 15953 상금 헌터 (0) | 2019.03.29 |
17090 미로탈출 (0) | 2019.03.28 |
(삼성) 14053 로봇청소기 (0) | 2019.03.28 |