Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ ตรวจสอบการเชื่อมต่อของ Directed Graph โดยใช้ BFS


ในการตรวจสอบการเชื่อมต่อของกราฟ เราจะพยายามสำรวจโหนดทั้งหมดโดยใช้อัลกอริธึมการข้ามผ่านใดๆ หลังจากเสร็จสิ้นการข้ามผ่าน หากมีโหนดใดที่ไม่ได้เข้าชม กราฟจะไม่เชื่อมต่อ

โปรแกรม C++ ตรวจสอบการเชื่อมต่อของ Directed Graph โดยใช้ BFS

สำหรับกราฟกำกับ เราจะเริ่มสำรวจจากทุกโหนดเพื่อตรวจสอบการเชื่อมต่อ บางครั้งขอบด้านหนึ่งอาจมีขอบด้านนอกเพียงด้านเดียว แต่ไม่มีขอบด้านใน ดังนั้นโหนดจะไม่ถูกเยี่ยมชมจากโหนดเริ่มต้นอื่นๆ

ในกรณีนี้ อัลกอริธึมการข้ามผ่านคือการข้ามผ่าน 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(กราฟ)

ป้อนข้อมูล − กราฟ

ผลผลิต − เป็นจริงหากเชื่อมต่อกราฟ

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.