Tuesday, 17 September 2013

Graph Using Matrix

HTML Online Editor Sample

 

#include<stdio.h>

#include<iostream>
#include<queue>
#include<stack>
using namespace std;
int adj[10][10];
bool visit[10];
int main()
{int v,e;
cout<<"\n enter vertex and edge";
cin>>v>>e;
int i,j;
while(e--)
{
cout<<"\n enter vertices between which you want an edge";
cin>>i>>j;
adj[i-1][j-1]=1;
}
 
for(i=0;i<v;i++)
for(j=0;j<v;j++)
if(adj[i][j]==1)
{cout<<"vertex\t "<<i+1<<" and vertex\t"<<j+1<<" connected";
cout<<endl;
}
queue<int> q;
q.push(0);int count=1;
int level=0;
cout<<"\n ++++++++++++++bfs of the graph is ++++++++++++++\n";
while(!q.empty())
{int x=q.front();
q.pop();
count--;
if(!visit[x])
{cout<<x+1<<"->\t";
visit[x]=true;}
 
for(int i=0;i<v;i++)
if(adj[x][i]&&!visit[i])
{q.push(i);level++;}
if(count==0)
{cout<<endl;count=level;}
 
}
for(int i=0;i<5;i++)
visit[i]=false;
cout<<"\n *************dfs of the graph is****************\n";
stack<int> s;
s.push(0);
while(!s.empty())
{int flag=0;
  int x=s.top();
  if(!visit[x])
  cout<<x+1<<endl;
  visit[x]=true;
 //s. pop();
  for(int i=0;i<v;i++){
  if(adj[x][i]==1&&!visit[i])
  {s.push(i);flag=1;break;}}
  if(flag==0)
  {
    x=s.top();
    s.pop();
 // visit[x]=true;
  }
}
return 0;
}

No comments:

Post a Comment