策码奔腾

BellmanFord贝尔曼-福特算法

import java.util.ArrayList;

import java.util.Scanner;

/**
* 贝尔曼-福特算法
*
* Bellman - ford算法是求含负权图的单源最短路径算法,效率较低。
* @author CEMABENTENG
*
*/
public class BellmanFord
{
  private static int n, m;

  private static final int MAXN = 100;

  private static final int INF = Integer.MAX_VALUE;

  private static ArrayList<Edge> edges = new ArrayList<Edge>();

  private static int[][] edge = new int[MAXN][MAXN];

  private static int[] dist = new int[MAXN];

  private static int[] path = new int[MAXN];

  public static void main(String[] args)
  {
    Scanner scan = new Scanner(System.in);
    while (scan.hasNext())
    {
      //点
      n = scan.nextInt();
      //边
      m = scan.nextInt();

      //初始化点
      for (int i = 0; i < n; i++)
      {
        for (int j = 0; j < n; j++)
        {
          if (i == j)
          {
            edge[i][j] = 0;
          }
          else
          {
            edge[i][j] = INF;
          }
        }
      }
      //初始化边
      for (int i = 0; i < m; i++)
      {
        //边左点
        int u = scan.nextInt();
        //边右点
        int v = scan.nextInt();
        //权
        int w = scan.nextInt();
        Edge edge_ = new BellmanFord.Edge();
        edge_.u = u;
        edge_.v = v;
        edge_.w = w;
        edge[u][v] = w;
        edges.add(edge_);
      }
      //查找0的距离
      bellman(1);
      for (int i = 0; i < n; i++)
      {
        System.out.println("从0到" + i + "的距离最短为 :" + dist[i]);
      }
    }
  }

  /**
  * 贝尔曼-福特算法
  * @param vo
  */
  public static void bellman(int vo)
  {
    int i, k;
    for (i = 0; i < n; i++)
    {
      //初始化所有最短距离
      dist[i] = INF;
      path[i] = -1;
    }
    //结果集的起点,起点距离为0
    dist[vo] = 0;
    //遍历点
    for (k = 1; k < n; k++)
    {
      //遍历边
      for (i = 0; i < m; i++)
      {
        Edge edge = edges.get(i);

/**
* 当前边的左点到原点距离有值,且边的左点到原点的值+当前权小于右点到原点的值,则更新右点到原点的值(即松弛算法)
*
* 每个单源最短路径算法中都会初始化,然后重复对边进行松弛的过程。
* 另外,松弛是改变最短路径和前趋的唯一方式。各个单源最短路径算法间区别在于对每条边进行松弛操作的次数,以及对边执行松弛操作的次序有所不同。在
*/
        if (dist[edge.u] != INF && dist[edge.u] + edge.w < dist[edge.v])
        {
          dist[edge.v] = dist[edge.u] + edge.w;
          path[edge.v] = edge.u;
        }
      }
    }
  }

  public static class Edge
  {
    int u, v, w;
  }

}

posted @ 2017-04-26 10:14  策码奔腾  阅读(1440)  评论(0编辑  收藏  举报
console.log('欢迎');