顶点之间的最短路径

时间:2016-12-10 08:59:01

标签: java graph nodes shortest-path

如何找到顶点之间的最短距离,我尝试在打印方法上设置最小条件,但它不会起作用。这是我目前的代码

  public void print() {

    for (int i = 0; i < jNode; i++) {
        System.out.print("   Node [" + i + "]");
        Node n = node[i];

        while (n != null) {
            System.out.print("\n            [" + i + "] -> [" + n.getData() + "] Distance" + n.getDistance());
            n = n.getNext();
        }
        System.out.println();
    }

}

public void addAdj(int head, int adj, int distance) {
    Node n = new Node(node[head], adj, distance);
    node[head] = n;
    current++;
    dt1[head][adj]++;
}

public class Node {


    private final int data;
    private final int distance;
    private final Node next;

    public Node(Node n, int dt, int distance) {
        data = dt;
        next = n;
        this.distance= distance;
    }


    public int getData() {
        return data;
    }


    public Node getNext() {
        return next;
    }


    public int getDistance() {
        return distance;
    }
}

public static void main(String s[]) {
    Graph g = new Graph(5);
    g.addAdj(0, 3, 1);
    g.addAdj(0, 1, 2);
    g.addAdj(1, 4, 4);
    g.addAdj(1, 2, 4);
    g.addAdj(2, 4, 8);
    g.addAdj(2, 1, 2);
    g.addAdj(4, 3, 3);}
  

此代码将向我们展示:

Node [0]

        [0] -> [1] distance 2
        [0] -> [3] distance 1

Node [1]

        [1] -> [2] distance 4
        [1] -> [4] distance 4

Node [2]
        [2] -> [1] distance 2
        [2] -> [4] distance 8

Node [3]

Node [4]

        [4] -> [3] distance 3
  

我的预期输出:

     

Node [0]到Node [3]

之间的最短距离

0 个答案:

没有答案