Java中的加权有向图实现&贝尔曼 - 福特

时间:2016-12-27 19:51:01

标签: java algorithm graph time-complexity bellman-ford

我试图找出在Java中实现加权有向图的最佳方法,这样我就可以将Bellman-Ford的运行时间保持为| V | * | E |。基本上我的问题是如何表示图中的边缘。

我已经看到了邻接矩阵的使用,但我似乎无法弄清楚如何使用邻接矩阵,同时将运行时间保持在O(V ^ 2)以下。我得到V ^ 2作为运行时间的原因是因为Bellman-Ford要求我们遍历所有边缘,但是为了获得我需要在整个矩阵中循环以获得所有边缘的边缘列表。无论如何使用邻接矩阵来获得比O(V ^ 2)时间更快的边缘列表?

或者我是否需要使用邻接列表?

2 个答案:

答案 0 :(得分:1)

您可以轻松地为Adjacency List实现一个类。以下是我经常用作邻接列表的类,这也很容易理解。它会将integer映射到linked list

class Adjacencylist {

    private Map<Integer, List<Integer>> adjacencyList;

    public Adjacencylist(int v){    //Constructor
        adjacencyList = new HashMap<Integer,List<Integer>>();
        for(int i=0;i<v;++i){
            adjacencyList.put(i, new LinkedList<Integer>());
        }
    }

    public void setEdge(int a,int b){    //method to add an edge
        List<Integer> edges=adjacencyList.get(a);
        edges.add(b);
    }

    public List<Integer> getEdge(int a){
        return adjacencyList.get(a);
    }

    public boolean contain(int a,int b){
        return adjacencyList.get(a).contains(b);
    }

    public int numofEdges(int a){
        return adjacencyList.get(a).size();
    }

    public void removeEdge(int a,int b){
        adjacencyList.get(a).remove(b);
    }

    public void removeVertex(int a){
        adjacencyList.get(a).clear();
    }

    public void addVertex(int a){
        adjacencyList.put(a, new LinkedList<Integer>());
    }
}

在您抱怨我需要实施加权图表之前,请考虑将HashMap映射到Integer。您可以将linked list替换为hash map来相应地更改功能。这样可以节省O(n ^ 2)时间复杂度。

答案 1 :(得分:0)

我的版本。在一个用例中,这对我来说效果很好。

public class DirectedWeightedGraph<E> {

// Map having Vertex as key and List of Edges as Value.
Map<Vertex<E>, List<Edge<E>>> adj = new HashMap<>();


public static class Vertex<E> {
    E value;

    public Vertex(E value) {
        this.value = value;
    }
}

public static class Edge<E> {
    E from;
    E to;
    double weight;

    public Edge(E from, E to, double weight) {
        this.from = from;
        this.to = to;
        this.weight = weight;
    }

}

public void addVertex(E value) {
    Vertex<E> v = new Vertex<E>(value);
    List<Edge<E>> edges = new ArrayList<>();
    this.adj.put(v, edges);
}

public void addEdge(E from, E to, double weight) {
    List<Edge<E>> fromEdges =  this.getEdges(from);
    List<Edge<E>> toEdges =  this.getEdges(from);

    // Add source vertex and then add edge
    if(fromEdges == null) {
        this.addVertex(from);
    }
    if(toEdges == null) {
        this.addVertex(to);
    }

    fromEdges.add(new Edge<E>(from, to, weight));
}

}

Example:

DirectedWeightedGraph <Integer> graph = new DirectedWeightedGraph<>();
graph.addEdge(1, 2, 10.0);
graph.addEdge(2,3,15.0);