당신은 화성 탐사 기계를 개발하는 프로그래머다. 그런데 화성은 에너지 공급원을 찾기가 힘들다.
그래서 에너지를 효율적으로 사용하고자 화성 탐사 기계가 출발 지점에서 목표 지점까지 이동할 때 항상 최적의 경로를 찾도록 개발해야 한다.
화성 탐사 기계가 존재하는 공간은 N x N 크기의 2차원 공간이며, 각각의 칸을 지나기 위한 비용(에너지 소모량)이 존재한다.
가장 왼쪽 위 칸인 [0][0] 위치에서 가장 오른쪽 아래 칸인 [N - 1][N - 1] 위치로 이동하는 최소 비용을 출력하는 프로그램을 작성하라.
화성 탐사 기계는 특정한 위치에서 상하좌우 인접한 곳으로 1칸씩 이동할 수 있다.
입력 조건
첫째 줄에 테스트 케이스의 수 T(1 <= T <= 10)가 주어진다.
매 테스트 케이스의 첫째 줄에는 탐사 공간의 크기를 의미하는 정수 N이 주어진다.
2 <= N <= 125
이어서 N개의 줄에 걸쳐 각 칸의 비용이 주어지며 공백으로 구분한다.
0 <= 각 칸의 비용 <= 9
출력 조건
각 테스트 케이스마다 [0][0]의 위치에서 [N - 1][N - 1]의 위치로 이동하는 최소 비용을 한 줄에 하나씩 출력한다.
입력 예시
3
3
5 5 4
3 9 1
3 2 7
5
3 7 2 0 1
2 8 0 9 1
1 2 1 8 1
9 8 9 2 0
3 6 5 1 5
7
9 0 5 1 1 5 3
4 1 2 1 6 5 3
0 7 6 1 6 8 5
1 1 7 8 3 2 3
9 4 0 7 6 4 1
5 8 3 2 4 8 3
7 4 8 4 8 3 4
출력예시
20
19
36
import java.io.*;
import java.util.*;
class Node implements Comparable<Node>{
private int x;
private int y;
private int distance;
public Node(int x, int y, int distance){
this.x = x;
this.y = y;
this.distance = distance;
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
public int getDistance(){
return this.distance;
}
@Override
public int compareTo(Node other){
return Integer.compare(this.distance, other.distance);
}
}
public class Main{
public static int[][] arr;
public static int[][] d;
public static int n;
public static int INF = (int)1e9;
public static int[] dx = {0, 0, -1 ,1};
public static int[] dy = {-1, 1, 0, 0};
public static void Dijkstra(){
PriorityQueue<Node>pq = new PriorityQueue<>();
// 시작점 초기화
d[0][0] = arr[0][0];
pq.offer(new Node(0, 0, arr[0][0]));
while(!pq.isEmpty()){
Node now = pq.poll();
int x = now.getX();
int y = now.getY();
int distance = now.getDistance();
if(d[x][y] < distance) continue;
// 상하좌우 판별
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 < n){
int cost = distance + arr[nx][ny];
if(d[nx][ny] > cost){
d[nx][ny] = cost;
pq.offer(new Node(nx, ny, cost));
}
}
}
}
}
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int cnt = Integer.parseInt(br.readLine());
// 테스트 케이스 수 만큼 반복
for(int c = 0 ; c < cnt; c++){
n = Integer.parseInt(br.readLine());
arr = new int[n][n];
for(int i = 0 ; i < n ; i++){
st = new StringTokenizer(br.readLine());
for(int j = 0 ; j < n ; j++ ){
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
d = new int[n][n];
for(int i = 0 ; i < n ; i++){
Arrays.fill(d[i], INF);
}
Dijkstra();
System.out.println(d[n-1][n-1]);
}
}
}
이 문제는 처음 (0, 0)부터 (n-1, n-1) 까지의 최단거리를 구하는 것이다.
이땐 다익스트라 알고리즘을 사용해야한다. 범위가 크기 때문이다.
이 문제를 구하기 위해선 상하좌우를 판단해야하기 때문에 dx, dy 를 선언하고 상하좌우를 확인 후에 범위에 맞고, 거리값이 작으면 우선순위 큐에 넣어주면 된다.