반응형
https://www.acmicpc.net/problem/1261
1261번: 알고스팟
첫째 줄에 미로의 크기를 나타내는 가로 크기 M, 세로 크기 N (1 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 미로의 상태를 나타내는 숫자 0과 1이 주어진다. 0은 빈 방을 의미하고, 1은 벽을 의미
www.acmicpc.net
#문제 간단 정리
다익스트라를 활용하자
#문제 해결 방법
벽을 부수는건 1 코스트가 들기 때문에
벽을 부수는 걸 우선으로 하는 우선순위 큐를 활용해서
bfs 를 사용 (다익스트라)
해서 문제를 풀면 된다
#전체 코드
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
const int INF = numeric_limits<int>::max();
int dx[4] = { -1, 1, 0, 0 };
int dy[4] = { 0, 0, 1, -1 };
vector<vector<int>> maze;
vector<vector<int>> cost;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> m >> n;
maze.resize(n, vector<int>(m, 0));
cost.resize(n, vector<int>(m, INF));
for (int i = 0; i < n; i++) {
string s;
cin >> s;
for (int j = 0; j < m; j++) {
maze[i][j] = s[j] - '0';
}
}
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<>> pq;
pq.push({0, {0, 0}});
cost[0][0] = 0;
while (!pq.empty()) {
int currentCost = pq.top().first;
int x = pq.top().second.first;
int y = pq.top().second.second;
pq.pop();
if (x == n - 1 && y == m - 1) {
cout << currentCost << '\n';
return 0;
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (0 <= nx && nx < n && 0 <= ny && ny < m) {
int nextCost = currentCost + (maze[nx][ny] == 1 ? 1 : 0);
if (nextCost < cost[nx][ny]) {
cost[nx][ny] = nextCost;
pq.push({nextCost, {nx, ny}});
}
}
}
}
return 0;
}
반응형
'[백준] > C++' 카테고리의 다른 글
백준 18879번 좌표 압축 [C++] (1) | 2024.04.28 |
---|---|
백준 2665번 미로만들기 [C++] (0) | 2024.04.14 |
백준 1584번 게임 [C++] (0) | 2024.04.12 |
백준 6126번 Cow Cash [C++] (0) | 2024.04.07 |
백준 4949번 균형잡힌 세상 [C++] (0) | 2024.04.03 |