【问题标题】:Reachability in graph - C图中的可达性 - C
【发布时间】:2016-05-22 04:49:06
【问题描述】:

我在邻接列表中实现了我的图表。当用户提供索引时,如何估计一个顶点与另一个顶点的可达性?

int isReachable(int nodes, int graph[nodes][nodes], int src, int dest) 

检查直接邻居很容易,但我在整体实现算法方面遇到了困难。

【问题讨论】:

  • 要计算一个节点是否可以从另一个节点到达,您需要在图上执行搜索。据推测,您应该适应您在课程早期学到的东西 - 例如,可以进行广度优先搜索或深度优先搜索来完成这项工作。
  • 你知道对邻接矩阵求平方会发生什么吗?

标签: c graph graph-algorithm


【解决方案1】:

代码来自:http://www.geeksforgeeks.org/transitive-closure-of-a-graph/

int reach[V][V], i, j, k;

    /* Initialize the solution matrix same as input graph matrix. Or
       we can say the initial values of shortest distances are based
       on shortest paths considering no intermediate vertex. */
    for (i = 0; i < V; i++)
        for (j = 0; j < V; j++)
            reach[i][j] = graph[i][j];

    /* Add all vertices one by one to the set of intermediate vertices.
      ---> Before start of a iteration, we have reachability values for
           all pairs of vertices such that the reachability values 
           consider only the vertices in set {0, 1, 2, .. k-1} as 
           intermediate vertices.
      ----> After the end of a iteration, vertex no. k is added to the 
            set of intermediate vertices and the set becomes {0, 1, .. k} */
    for (k = 0; k < V; k++)
    {
        // Pick all vertices as source one by one
        for (i = 0; i < V; i++)
        {
            // Pick all vertices as destination for the
            // above picked source
            for (j = 0; j < V; j++)
            {
                // If vertex k is on a path from i to j,
                // then make sure that the value of reach[i][j] is 1
                reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);
            }
        }
    }

    // Print the shortest distance matrix
    printSolution(reach);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多