가중치가 있는 그래프에서 출발점 ~ 목표점까지의 최단거리를 구할 때 사용하는 알고리즘
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
public class 배달 {
static class Point implements Comparable<Point> {
int to, weight;
Point(int to, int weight) {
this.to = to;
this.weight = weight;
}
@Override
public int compareTo(Point o) {
return this.weight - o.weight;
}
}
public static void main(String[] args) {
int N = 5;
int[][] road = {{1,2,1},{2,3,3},{5,2,2},{1,4,2},{5,3,1},{5,4,2}};
int K = 3;
ArrayList<ArrayList<Point>> adj = new ArrayList<ArrayList<Point>>();
PriorityQueue<Point> pq = new PriorityQueue<Point>();
int[] arr = new int[N+1];
Arrays.fill(arr, Integer.MAX_VALUE);
for(int i=0; i<=N; ++i) adj.add(new ArrayList<Point>());
for(int i=0; i<road.length; i++) {
int x = road[i][0];
int y = road[i][1];
int z = road[i][2];
adj.get(x).add(new Point(y, z));
adj.get(y).add(new Point(x, z));
}
arr[1] = 0;
pq.offer(new Point(1, 0));
while(!pq.isEmpty()) {
Point cur = pq.poll();
for(Point p : adj.get(cur.to)) {
if(arr[p.to] > arr[cur.to] + p.weight) {
arr[p.to] = arr[cur.to] + p.weight;
pq.offer(p);
}
}
}
int count = 0;
for(int i=0; i<arr.length; i++) {
if(arr[i] <= K) {
count ++;
}
}
System.out.println(count);
}
}