Design an algorithm that decides whether a given undirected

Design an algorithm that decides whether a given undirected graph is a tree. The algorithm should run in time O(n + m), where n is the number of nodes and m is the number of edges in the input graph.

Solution

Actually in tree m < n so I just created Adjecency matrix of the graph and counted number of 1 in the graph.

If number of 1\'s are greater than number of edges then it is not the tree otherwise it is tree.

This code is in c++

#include <iostream>

/* run this program using the console pauser or add your own getch, system(\"pause\") or input loop */
using namespace std;
int main(int argc, char** argv) {
   int n,m,i,j;
   static int count=0;
   int ver[20][20];
   cout << \"Enter the number of vertices of the graph\ \";
   cin >> n;

       cout << \"\\t\\tEnter adjecency list of a GRAPH :\ \";
       for(i=0;i<n;i++){
           for(j=0;j<n;j++){
               cout << i << \" TO \" << j << \"--->\";
               cin >> ver[i][j];
               cout << \"\ \";
           }
       }
       cout << \"\\t\\tgiven GRAPH is:\ \";
       for(i=0;i<n;i++){
           for(j=0;j<n;j++){
               cout << ver[i][j] << \"\\t\";
           }
           cout << \"\ \";
       }
       for(i=0;i<n;i++){
           for(j=0;j<n;j++){
               if(ver[i][j] == 1)
                   count++;
           }
       }
       if(count <n )
           cout << \"\\tGRAPH is TREE\ \";
       else
           cout << \"\\tGRAPH is NOT TREE\ \";      
  
  
   return 0;
}

Design an algorithm that decides whether a given undirected graph is a tree. The algorithm should run in time O(n + m), where n is the number of nodes and m is

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site