BFSを使用して有向グラフの接続性をチェックするC++プログラム
グラフの接続性を確認するために、トラバーサルアルゴリズムを使用してすべてのノードをトラバースしようとします。トラバーサルの完了後、アクセスされていないノードがある場合、グラフは接続されていません。
有向グラフの場合、接続を確認するためにすべてのノードからトラバースを開始します。 1つのエッジに外側のエッジのみがあり、内側のエッジがない場合があるため、ノードは他の開始ノードからアクセスされません。
この場合、トラバーサルアルゴリズムは再帰的なBFSトラバーサルです。
入力 −グラフの隣接行列
| 0 | 1 | 0 | 0 | 0 |
| 0 | 0 | 1 | 0 | 0 |
| 0 | 0 | 0 | 1 | 1 |
| 1 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 0 | 0 |
出力 −グラフが接続されています。
アルゴリズム
トラバース、訪問済み)
入力 :開始ノードと訪問ノードは、どのノードが訪問されたかをマークします。
出力 :接続されているすべての頂点をトラバースします。
Begin mark s as visited insert s into a queue Q until the Q is not empty, do u = node that is taken out from the queue for each node v of the graph, do if the u and v are connected, then if u is not visited, then mark u as visited insert u into the queue Q. done done End
isConnected(graph)
入力 −グラフ。
出力 −グラフが接続されている場合はtrue。
Begin
define visited array
for all vertices u in the graph, do
make all nodes unvisited
traverse(u, visited)
if any unvisited node is still remaining, then
return false
done
return true
End サンプルコード
#include<iostream>
#include<queue>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 0, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 1, 1},
{1, 0, 0, 0, 0},
{0, 1, 0, 0, 0}};
void traverse(int s, bool visited[]) {
visited[s] = true; //mark v as visited
queue<int> que;
que.push(s);//insert s into queue
while(!que.empty()) {
int u = que.front(); //delete from queue and print
que.pop();
for(int i = 0; i < NODE; i++) {
if(graph[i][u]) {
//when the node is non-visited
if(!visited[i]) {
visited[i] = true;
que.push(i);
}
}
}
}
}
bool isConnected() {
bool *vis = new bool[NODE];
//for all vertex u as start point, check whether all nodes are visible or not
for(int u; u < NODE; u++) {
for(int i = 0; i < NODE; i++)
vis[i] = false; //initialize as no node is visited
traverse(u, vis);
for(int i = 0; i < NODE; i++) {
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
}
return true;
}
int main() {
if(isConnected())
cout << "The Graph is connected.";
else
cout << "The Graph is not connected.";
} 出力
The Graph is connected.
-
有向グラフにオイラー閉路が含まれているかどうかを確認するC++プログラム
オイラーサイクル/回路はパスです。これにより、すべてのエッジを1回だけ訪問できます。同じ頂点を複数回使用できます。オイラー回路は、特殊なタイプのオイラーパスです。オイラーパスの開始頂点がそのパスの終了頂点にも接続されている場合、それはオイラー回路と呼ばれます。 グラフがオイラーであるかどうかを確認するには、2つの条件を確認する必要があります- グラフを接続する必要があります。 各頂点の次数と次数は同じである必要があります。 入力 −グラフの隣接行列。 0 1 0 0 0 0 0 1 0 0 0 0 0
-
DFSを使用して有向グラフの接続性をチェックするC++プログラム
グラフの接続性を確認するために、トラバーサルアルゴリズムを使用してすべてのノードをトラバースしようとします。トラバーサルの完了後、アクセスされていないノードがある場合、グラフは接続されていません。 有向グラフの場合、接続を確認するためにすべてのノードからトラバースを開始します。 1つのエッジに外向きのエッジのみがあり、内向きのエッジがない場合があるため、他の開始ノードからノードにアクセスできなくなります。 この場合、トラバーサルアルゴリズムは再帰的なDFSトラバーサルです。 入力 :グラフの隣接行列 0 1 0 0 0 0 0 1 0