C++ 程式以查詢圖的傳遞閉包


如果給定了一個有向圖,判斷在給定的圖中,對於所有頂點對 (i, j),頂點 j 是否可以從另一個頂點 i 處到達。可到達意味著從頂點 i 到 j 有路徑。這個可達矩陣被稱為圖的傳遞閉包。Warshall 演算法常用於查詢指定圖 G 的傳遞閉包。下面是一個 C++ 程式來實現此演算法。

演算法

Begin
   1. Take maximum number of nodes as input.
   2. For Label the nodes as a, b, c…..
   3. To check if there any edge present between the nodes
   make a for loop:
   // ASCII code of a is 97
   for i = 97 to (97 + n_nodes)-1
      for j = 97 to (97 + n_nodes)-1
         If edge is present do,
            adj[i - 97][j - 97] = 1
         else
            adj[i - 97][j - 97] = 0
      End loop
   End loop.
   4. To print the transitive closure of graph:
   for i = 0 to n_nodes-1
      c = 97 + i
   End loop.
   for i = 0 to n_nodes-1
      c = 97 + i
      for j = 0 to n_nodes-1
         Print adj[I][j]
      End loop
   End loop
End

示例

#include<iostream>
using namespace std;
const int n_nodes = 20;
int main()
{
   int n_nodes, k, n;
   char i, j, res, c;
   int adj[10][10], path[10][10];
   cout << "\n\tMaximum number of nodes in the graph :";
   cin >> n;
   n_nodes = n;
   cout << "\nEnter 'y' for 'YES' and 'n' for 'NO' \n";
   for (= 97; i < 97 + n_nodes; i++)
      for (= 97; j < 97 + n_nodes; j++)
   {
      cout << "\n\tIs there an edge from " << i << " to "
      << j << " ? ";
      cin >> res;
      if (res == 'y')
         adj[- 97][- 97] = 1;
      else
         adj[- 97][- 97] = 0;
   }
   cout << "\n\nTransitive Closure of the Graph:\n";
   cout << "\n\t\t\t ";
   for (= 0; i < n_nodes; i++)
   {
      c = 97 + i;
      cout << c << " ";
   }
   cout << "\n\n";
   for (int i = 0; i < n_nodes; i++)
   {
      c = 97 + i;
      cout << "\t\t\t" << c << " ";
      for (int j = 0; j < n_nodes; j++)
      cout << adj[i][j] << " ";
      cout << "\n";
   }
   return 0;
}

輸出

Maximum number of nodes in the graph :4
Enter 'y' for 'YES' and 'n' for 'NO'
Is there an edge from a to a ? y
Is there an edge from a to b ?y
Is there an edge from a to c ? n
Is there an edge from a to d ? n
Is there an edge from b to a ? y
Is there an edge from b to b ? n
Is there an edge from b to c ? y
Is there an edge from b to d ? n
Is there an edge from c to a ? y
Is there an edge from c to b ? n
Is there an edge from c to c ? n
Is there an edge from c to d ? n
Is there an edge from d to a ? y
Is there an edge from d to b ? n
Is there an edge from d to c ? y
Is there an edge from d to d ? n
Transitive Closure of the Graph:
a b c d
a 1 1 0 0
b 1 0 1 0
c 1 0 0 0
d 1 0 1 0

更新於:30- 七月-2019

401 次瀏覽

開啟你的 職業 生涯

完成課程即可獲得認證

開始吧
廣告