조건
시간 복잡도
구현 방법
예시 : 링크 참고
조건
시간 복잡도 : O(mn)
구현 방법
예시 : 링크 참고
조건
시간 복잡도 : O(n^3)
구현 방법
answer[3][2] = Math.min(answer[3][2], answer[3][1] + answer[1][2]);
answer[3][4] = Math.min(answer[3][4], answer[3][1] + answer[1][4]);
...
public class Solution {
private static final int START_NODE_INDEX = 0;
public int[] solution(int N, int[][] road, int K) {
int[][] matrix = makeGraphMatrix(N, road);
int[] minimumDistance = calculateMinimumDistance(matrix, START_NODE_INDEX);
return minimumDistance;
}
private int[][] makeGraphMatrix(int N, int[][] roads) {
int[][] matrix = new int[N][N];
for (int[] road : roads) {
// 같은 길 정보 중복 시, 짧은 길을 선택하도록 함
if (matrix[road[0]-1][road[1]-1] != 0 && matrix[road[0]-1][road[1]-1] <= road[2]) {
continue;
}
matrix[road[0]-1][road[1]-1] = road[2];
matrix[road[1]-1][road[0]-1] = road[2];
}
return matrix;
}
private int[] calculateMinimumDistance(int[][] matrix, int startIndex) {
// answer : 정답을 가지고 있음
int[] answer = new int[matrix.length];
Arrays.fill(answer, Integer.MAX_VALUE);
answer[startIndex] = 0;
// isChecked : 현재 방문했는제를 확인함
boolean[] isChecked = new boolean[matrix.length];
PriorityQueue<Node> queue = new PriorityQueue<>();
queue.add(new Node(startIndex, 0));
while (!queue.isEmpty()) {
Node currentNode = queue.remove();
int currentIndex = currentNode.getNodeIndex();
if (isChecked[currentNode.getNodeIndex()]) {
continue;
}
isChecked[currentNode.getNodeIndex()] = true;
for (int i=0; i < matrix.length; i++) {
if (matrix[currentIndex][i] == 0) {
continue;
}
if (currentNode.getDistance() + matrix[currentIndex][i] < answer[i]) {
answer[i] = currentNode.getDistance() + matrix[currentIndex][i];
queue.add(new Node(i, answer[i]));
}
}
}
return answer;
}
}
class Node implements Comparable<Node> {
private int nodeIndex;
private int distance;
Node(int nodeIndex, int distance) {
this.nodeIndex = nodeIndex;
this.distance = distance;
}
public int getDistance() {
return distance;
}
public int getNodeIndex() {
return nodeIndex;
}
@Override
public int compareTo(Node o) {
return this.distance - o.distance;
}
}