Wednesday, April 28, 2021

Shortest Cycle in a Directed Graph

https://stackoverflow.com/questions/3911626/find-cycle-of-shortest-length-in-a-directed-graph-with-positive-weights
 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package ShortestCycle;

import java.util.*;
public class Main {
    public static void main(String[] args) {
        System.out.println("Shortest Cycle");

        Map<Integer, List<Integer>> map = new HashMap<>();
        map.put(0, new ArrayList<>());
        map.put(1, new ArrayList<>());
        map.put(2, new ArrayList<>());
        map.put(3, new ArrayList<>());
        map.put(4, new ArrayList<>());

        map.get(0).add(1);
        map.get(0).add(2);
        map.get(1).add(3);
        map.get(2).add(4);
        map.get(3).add(0);
        map.get(4).add(3);

        List<Integer> prev = new ArrayList<>();
        prev.add(3);

        int[] dist = new int[5];
        Arrays.fill(dist, Integer.MAX_VALUE);
        //dist, index
        PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[0]-b[0]);
        pq.add(new int[]{0, 0});
        while(!pq.isEmpty()){
            int[] top = pq.poll();
            int d = top[0], index = top[1];
            if(d<dist[index]){
                dist[index] = d;
                if(map.containsKey(index)){
                    for(int next : map.get(index)){
                        if(d+1 < dist[next]){
                            pq.add(new int[]{d+1, next});
                        }
                    }
                }
            }
        }

        int min = Integer.MAX_VALUE;
        for(int p : prev){
            min = Math.min(min, dist[p]);
        }
        System.out.println(min+1);
    }
}

No comments:

Post a Comment