승형님의 블로그
백준 2665번, 미로만들기 본문
https://www.acmicpc.net/problem/2665
2665번: 미로만들기
첫 줄에는 한 줄에 들어가는 방의 수 n(1 ≤ n ≤ 50)이 주어지고, 다음 n개의 줄의 각 줄마다 0과 1이 이루어진 길이가 n인 수열이 주어진다. 0은 검은 방, 1은 흰 방을 나타낸다.
www.acmicpc.net
요약
(1,1) 지점에서 (N,N) 지점으로 이어지는 미로를 만든다.
1. 미리 정해진 방의 상태가 주어진다. 이때, 흰 방은 조작 없이 지나갈 수 있고, 검은 방은 1회의 조작 후 지나갈 수 있다.
2. 인접한 흰 방으로의 이동은 비용이 0, 인접한 검은 방으로의 이동은 비용이 1인 그래프로 바꾸어 다익스트라로 풀이할 수 있다.
3. 다익스트라의 시간 복잡도는 $O\left ( \left| E\right|log\left|E \right| \right )$이고, 정점의 개수가 최대 50 * 50 = 2500개, 간선의 개수가 최대 4 * V이므로 1초 안에 처리 가능하다.
#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
struct cmp {
bool operator() (pair<int, pair<int, int>> A, pair<int, pair<int, int>> B) {
return A.first > B.first;
}
};
int N;
int arr[50][50];
int dx[4] = { 1, -1, 0, 0 };
int dy[4] = { 0, 0, 1, -1 };
int dist[50][50];
void Dijkstra(int x, int y);
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> N;
for (int i = 0; i < N; i++) {
string s;
cin >> s;
for (int j = 0; j < N; j++) {
arr[i][j] = s[j] - '0';
arr[i][j] ^= 1;
}
}
Dijkstra(0, 0);
cout << dist[N - 1][N - 1];
return 0;
}
void Dijkstra(int x, int y) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) dist[i][j] = INF;
}
priority_queue <pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, cmp> pq;
dist[y][x] = 0;
pq.push({ 0, {x,y} });
while (pq.size()) {
int now_x = pq.top().second.first;
int now_y = pq.top().second.second;
int val = pq.top().first;
pq.pop();
if (dist[now_y][now_x] < val) continue;
for (int i = 0; i < 4; i++) {
int nx = now_x + dx[i];
int ny = now_y + dy[i];
if (nx < 0 || nx > N - 1 || ny < 0 || ny > N - 1) continue;
int new_val = val + arr[ny][nx];
if (dist[ny][nx] > new_val) {
dist[ny][nx] = new_val;
pq.push({ new_val, {nx,ny} });
}
}
}
}
'Problem Solving > 백준' 카테고리의 다른 글
백준 20046번, Road Reconstruction (0) | 2022.11.24 |
---|---|
백준 2423번, 전구를 켜라 / Switch the Lamp On (0) | 2022.11.24 |
백준 13912번, 외계 생물 (0) | 2022.10.08 |
백준 16565번, N포커 (0) | 2022.10.07 |
백준 1007번, 벡터 매칭 (0) | 2022.09.29 |
Comments