문제 링크입니다: https://www.acmicpc.net/problem/4485
4485번: 녹색 옷 입은 애가 젤다지?
문제 젤다의 전설 게임에서 화폐의 단위는 루피(rupee)다. 그런데 간혹 '도둑루피'라 불리는 검정색 루피도 존재하는데, 이걸 획득하면 오히려 소지한 루피가 감소하게 된다! 젤다의 전설 시리즈의 주인공, 링크는 지금 도둑루피만 가득한 N x N 크기의 동굴의 제일 왼쪽 위에 있다. [0][0]번 칸이기도 하다. 왜 이런 곳에 들어왔냐고 묻는다면 밖에서 사람들이 자꾸 "젤다의 전설에 나오는 녹색 애가 젤다지?"라고 물어봤기 때문이다. 링크가 녹색 옷을 입
www.acmicpc.net
기존에 풀었던 다익스트라 문제들과는 달리 2차원 행렬을 입력받아 풀어야했던 문제였습니다.
전형적인 BFS 문제처럼 풀면 되고 여기에 가중치의 대소 관계만 고려한다면 쉽게 풀 수 있을 문제였습니다.
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 <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <functional> | |
#include <queue> | |
#include <cstring> | |
using namespace std; | |
const int INF = 987654321; | |
const int MAX = 125 + 1; | |
typedef struct | |
{ | |
int y, x; | |
}Dir; | |
Dir moveDir[4] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} }; | |
int graph[MAX][MAX]; | |
int dist[MAX][MAX]; | |
bool visited[MAX][MAX]; | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
int cnt = 1; | |
while (1) | |
{ | |
int N; | |
cin >> N; | |
if (N == 0) | |
break; | |
// memset이 INF에 대해서는 정상 작동 X | |
for (int i = 0; i < N; i++) | |
for (int j = 0; j < N; j++) | |
dist[i][j] = INF; | |
memset(visited, false, sizeof(visited)); | |
for (int i = 0; i < N; i++) | |
for (int j = 0; j < N; j++) | |
cin >> graph[i][j]; | |
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> pq; | |
pq.push({ 0, {0, 0} }); | |
visited[0][0] = true; | |
while (!pq.empty()) | |
{ | |
int y = pq.top().second.first; | |
int x = pq.top().second.second; | |
int cost = pq.top().first; | |
pq.pop(); | |
for (int i = 0; i < 4; i++) | |
{ | |
int nextY = y + moveDir[i].y; | |
int nextX = x + moveDir[i].x; | |
int nextCost = cost + graph[nextY][nextX]; | |
// 범위 내에 있고 | |
if(0 <= nextY && nextY < N && 0 <= nextX && nextX < N) | |
// 아직 방문하지 않았으며, 누적합이 더 적을 때에만 | |
if (!visited[nextY][nextX] && dist[nextY][nextX] > nextCost) | |
{ | |
visited[nextY][nextX] = true; | |
dist[nextY][nextX] = nextCost; | |
pq.push({ nextCost, {nextY, nextX} }); | |
} | |
} | |
} | |
// 초기 우선순위 큐에 값을 넣을 때 graph[0][0]은 처리 안했으므로 같이 더해줘야한다. | |
cout << "Problem " << cnt++ << ": " << graph[0][0] + dist[N - 1][N - 1] << "\n"; | |
} | |
return 0; | |
} |


개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 17176번 암호해독기 (2) | 2019.05.23 |
---|---|
백준 5817번 고통받는 난쟁이들 (0) | 2019.05.22 |
백준 1238번 파티 (0) | 2019.05.22 |
백준 12116번 Uzastopni (0) | 2019.05.15 |
백준 12115번 Baza (0) | 2019.05.15 |