Пример #1
0
	void Start () {
      
        int s = 0;
        EdgeWeightedDigraph G = new EdgeWeightedDigraph(txt);

        BellmanFordSP sp = new BellmanFordSP(G, s);

        // print negative cycle
        if (sp.hasNegativeCycle())
        {
            foreach (DirectedEdge e in sp.negativeCycle())
                print(e);
        }

        // print shortest paths
        else
        {
            for (int v = 0; v < G.V(); v++)
            {
                if (sp.hasPathTo(v))
                {
                    string str=(s+" to "+ v+"  Distance="+ sp.DistTo(v)+"     ");
                    foreach (DirectedEdge e in sp.PathTo(v))
                    {
                       str+=(e + "   ");
                    }
                   print(str);
                }
                else
                {
                   print(s+" to "+ v+"           no path\n");
                }
            }
        }
    }
Пример #2
0
    /**/ public static void main(string[] strarr)
    {
        In  i  = new In(strarr[0]);
        int i2 = Integer.parseInt(strarr[1]);
        EdgeWeightedDigraph edgeWeightedDigraph = new EdgeWeightedDigraph(i);
        BellmanFordSP       bellmanFordSP       = new BellmanFordSP(edgeWeightedDigraph, i2);

        if (bellmanFordSP.hasNegativeCycle())
        {
            Iterator iterator = bellmanFordSP.negativeCycle().iterator();
            while (iterator.hasNext())
            {
                DirectedEdge obj = (DirectedEdge)iterator.next();
                StdOut.println(obj);
            }
        }
        else
        {
            for (int j = 0; j < edgeWeightedDigraph.V(); j++)
            {
                if (bellmanFordSP.hasPathTo(j))
                {
                    StdOut.printf("%d to %d (%5.2f)  ", new object[]
                    {
                        Integer.valueOf(i2),
                        Integer.valueOf(j),
                        java.lang.Double.valueOf(bellmanFordSP.distTo(j))
                    });
                    Iterator iterator2 = bellmanFordSP.pathTo(j).iterator();
                    while (iterator2.hasNext())
                    {
                        DirectedEdge obj2 = (DirectedEdge)iterator2.next();
                        StdOut.print(new StringBuilder().append(obj2).append("   ").toString());
                    }
                    StdOut.println();
                }
                else
                {
                    StdOut.printf("%d to %d           no path\n", new object[]
                    {
                        Integer.valueOf(i2),
                        Integer.valueOf(j)
                    });
                }
            }
        }
    }