| 109 | } |
| 110 | |
| 111 | class ImprovedDijkstra { |
| 112 | private int N; |
| 113 | private ArrayList<Node>[] graph; |
| 114 | |
| 115 | private final static int INF = Integer.MAX_VALUE; |
| 116 | private int[] D; |
| 117 | |
| 118 | public ImprovedDijkstra(int N) { |
| 119 | this.N = N; |
| 120 | graph = new ArrayList[N+1]; |
| 121 | for (int i = 1; i <= N; i++) graph[i] = new ArrayList<>(); |
| 122 | D = new int[N+1]; |
| 123 | for (int i = 1; i <= N; i++) D[i] = INF; |
| 124 | } |
| 125 | |
| 126 | public void setGraph(int i, int j, int w) { |
| 127 | graph[i].add(new Node(j, w)); |
| 128 | } |
| 129 | |
| 130 | public void printGraph() { |
| 131 | for (int i = 1; i <= N; i++) { |
| 132 | for (Node n : graph[i]) { |
| 133 | System.out.println(i + " --" + n.distance + "--> " + n.index); |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | public void getShortestDistance(int S) { |
| 139 | PriorityQueue<Node> pq = new PriorityQueue<>(((o1, o2) -> o1.distance - o2.distance)); |
| 140 | |
| 141 | D[S] = 0; |
| 142 | pq.offer(new Node(S, 0)); |
| 143 | |
| 144 | while (!pq.isEmpty()) { |
| 145 | Node current = pq.poll(); |
| 146 | if (current.distance > D[current.index]) continue; |
| 147 | |
| 148 | for (Node next : graph[current.index]) { |
| 149 | if (D[next.index] > D[current.index] + next.distance) { |
| 150 | D[next.index] = D[current.index] + next.distance; |
| 151 | pq.offer(new Node(next.index, D[next.index])); |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | printDistance(); |
| 157 | } |
| 158 | |
| 159 | public void getShortestDistance2(int S) { // INF = -1 로 초기화했을 때 |
| 160 | /* @Hee-Jae |
| 161 | - D 배열을 INF 대신 -1 로 초기화시킨다. |
| 162 | - 한 번도 방문하지 않은 노드에 대해서만 D 배열을 갱신하고 우선순위 큐에 넣어가며 탐색한다. |
| 163 | (우선순위 큐의 특성상 최저 비용으로 갈 수 있는 노드가 계속 큐의 제일 앞에 있기 때문에 '이 노드를 방문했는가?' 라는 조건만 판단해 준다면 Distance를 비교하지 않고도 최단경로를 구할 수 있다.) |
| 164 | - INF 값을 설정해주지 않아도 되기 때문에 Distance가 INF를 넘어가게 되는 경우를 생각하지 않아도 된다는 장점이 있다. |
| 165 | */ |
| 166 | PriorityQueue<Node> pq = new PriorityQueue<>(((o1, o2) -> o1.distance - o2.distance)); |
| 167 | |
| 168 | pq.offer(new Node(S, 0)); |
nothing calls this directly
no outgoing calls
no test coverage detected