解法一:Dijkstra

  1. import java.util.*;
  2. class Solution {
  3. public int networkDelayTime(int[][] times, int N, int K) {
  4. Point[] points = new Point[N + 1];
  5. for (int i = 1; i <= N; ++i) {
  6. points[i] = new Point(i);
  7. }
  8. for (int[] time : times) {
  9. points[time[0]].next.add(new int[]{time[1], time[2]});
  10. }
  11. Comparator<Integer> comparator = new Comparator<Integer>() {
  12. @Override
  13. public int compare(Integer o1, Integer o2) {
  14. return points[o1].dis - points[o2].dis;
  15. }
  16. };
  17. PriorityQueue<Integer> heap = new PriorityQueue<Integer>(comparator);
  18. points[K].dis = 0;
  19. heap.offer(K);
  20. int cnt = 0;
  21. while (!heap.isEmpty()) {
  22. int id = heap.poll();
  23. if (points[id].isVisited) {
  24. continue;
  25. }
  26. if (++cnt == N) {
  27. break;
  28. }
  29. points[id].isVisited = true;
  30. for (int[] line : points[id].next) {
  31. if (points[line[0]].isVisited) {
  32. continue;
  33. }
  34. points[line[0]].dis = Math.min(points[line[0]].dis, points[id].dis + line[1]);
  35. heap.offer(line[0]);
  36. }
  37. }
  38. int max = 0;
  39. for (int i = 1; i <= N; ++i) {
  40. max = Math.max(max, points[i].dis);
  41. }
  42. if (max == Integer.MAX_VALUE) {
  43. return -1;
  44. } else {
  45. return max;
  46. }
  47. }
  48. }
  49. class Point {
  50. int id;
  51. int dis;
  52. boolean isVisited;
  53. List<int[]> next;
  54. Point(int id) {
  55. this.id = id;
  56. dis = Integer.MAX_VALUE;
  57. isVisited = false;
  58. next = new ArrayList<>();
  59. }
  60. }

解法二:SPFA

  1. import java.util.*;
  2. class Solution {
  3. public int networkDelayTime(int[][] times, int N, int K) {
  4. Point[] points = new Point[N + 1];
  5. for (int i = 1; i <= N; ++i) {
  6. points[i] = new Point(i);
  7. }
  8. for (int[] time : times) {
  9. points[time[0]].next.add(new int[]{time[1], time[2]});
  10. }
  11. Queue<Integer> queue = new LinkedList<>();
  12. points[K].dis = 0;
  13. queue.offer(K);
  14. while (!queue.isEmpty()) {
  15. int id = queue.poll();
  16. points[id].isVisited = false;
  17. for (int[] line : points[id].next) {
  18. int cur = points[id].dis + line[1];
  19. if (points[line[0]].dis > cur) {
  20. points[line[0]].dis = cur;
  21. if (!points[line[0]].isVisited) {
  22. points[line[0]].isVisited = true;
  23. queue.offer(line[0]);
  24. }
  25. }
  26. }
  27. }
  28. int max = 0;
  29. for (int i = 1; i <= N; ++i) {
  30. max = Math.max(max, points[i].dis);
  31. }
  32. if (max == Integer.MAX_VALUE) {
  33. return -1;
  34. } else {
  35. return max;
  36. }
  37. }
  38. }
  39. class Point {
  40. int id;
  41. int dis;
  42. boolean isVisited;
  43. List<int[]> next;
  44. Point(int id) {
  45. this.id = id;
  46. dis = Integer.MAX_VALUE;
  47. isVisited = false;
  48. next = new ArrayList<>();
  49. }
  50. }