In: Computer Science
In this assignment, you will implement Breadth First Search (BFS). The input to your program is a graph in the adjacency list format. The input graph has at most 100 vertices. Your program must initiate a BFS from vertex 2 of the graph. If the graph is connected, your program must output “Graph is connected”. If the graph is disconnected, your program must output “Graph is not connected”. Your program should read from an input file: data2.txt and write to the output file: out2.txt.
Your program should be written in C or C++. You can use STL for a queue but not for a graph.
Input Example
1 3 4
2 4
3 1 4
4 2 1 3
1 2 4
2 1 3
3 2 4
4 1 3
1 2
2 1
3 4
4 3
Hi,
we used fstream for reading and writing into file
Below is the c++ implementation code:
#include<bits/stdc++.h>
#include<iostream>
#include <fstream>
#define NODE 100
using namespace std;
int graph[NODE][NODE];
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()
{
    int n;
    cin>>n; // number of vertices
    // now to read and write file
    freopen("data2.txt","r",stdin);
    freopen("out2.txt","w",stdout);
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            cin>>graph[i][j];
        }
    }
   if(isConnected())
      cout << "The Graph is connected.";
   else
      cout << "The Graph is not connected.";
}