接下来如何计算?

时间:2019-04-08 11:54:36

标签: c# algorithm dictionary floyd-warshall

所以我正在实现Floyd-Warshall算法。在每个“ Ex”上,缺少一些代码,但我将其全部填入。该代码仍然不正确,我也不知道为什么。

如果邻接矩阵不是无穷大,那么next[i,j]应该是j

/// <summary>
/// EXERCISE 5: Floyd-Warshall Algorithm
/// </summary>
///
/// <param name="adjacencyMatrix">the adjacency matrix representing the graph</param>
/// <returns>a tuple containing 1. the distance matrix, 2. the next matrix</returns>
static Tuple<double[,], int[,]> FloydWarshall(double[,] adjacencyMatrix)
{
  var numVertices = adjacencyMatrix.GetLength(0);

  double[,] dist = new double[numVertices, numVertices];

  int[,] next = new int[numVertices, numVertices];

  for (int i = 0; i < numVertices; i++)
  {
    for (int j = 0; j < numVertices; j++)
    {
      if (i == j)
      {
        // TODO: Ex5.1; dist[i, j] = ?

        dist[i, j] = 0;
      }
      else
      {
        // TODO: EX5.2; dist[i, j] = ?

        dist[i, j] = adjacencyMatrix[i,j];
      }

      if (adjacencyMatrix[i, j] != Double.PositiveInfinity)
      {
        // TODO: Ex5.3; next[i, j] = ?

        next[i, j] = j;
      }
      else
      {
        next[i, j] = -1;
      }
    }
  }

  for (int k = 0; k < numVertices; k++)
  {
    for (int i = 0; i < numVertices; i++)
    {
      for (int j = 0; j < numVertices; j++)
      {
        //if (? < ?) { ... }
        // TODO: Ex5.4
        if (dist[i, k] + dist[k, j] < dist[i, j])
        {
          dist[i, j] = dist[i, k] + dist[k, j];
          next[i, j] = next[i, k];
        }
      }
    }
  }

  return new Tuple<double[,], int[,]>(dist, next);
}

0 个答案:

没有答案