1. 程式人生 > >有向圖的鄰接表儲存

有向圖的鄰接表儲存

#include<iostream>
#include<stack> 
using namespace std;
stack<int> curStack;
struct ArcNode//邊表節點 
{
int data;
ArcNode *next;
 };
 struct VertexNode//頂點表節點 
 {
  char vertex;
ArcNode *firstedge;
 };
 const int MaxSize=10;//圖最大頂點數 
 class Picture
 {
private:
 VertexNode a[MaxSize];
 int sideNumber,dotNumber;
 
public:
Picture();
bool visited[MaxSize];
int getdotNumber();
void outputDot();
void outputTable();
void renovate();
void DFSTraverse(int v);//深度優先遍歷
void BFSTraverse(int v);//廣度優先遍歷
};
Picture::Picture()
{
int sideA,sideB;
cin>>dotNumber>>sideNumber;
for(int i=0;i<dotNumber;i++)
{
cin>>a[i].vertex;
a[i].firstedge=NULL;
}
for(int i=0;i<sideNumber;i++)
{
cin>>sideA>>sideB;
ArcNode *s=new ArcNode;
s->data=sideB;
s->next=a[sideA].firstedge;
a[sideA].firstedge=s;
visited[i]=false;

}
int Picture::getdotNumber()
{
return dotNumber;
}
void Picture::renovate()
{
for(int i=0;i<dotNumber;i++)
{
visited[i]=false;
}
}
void Picture::outputDot()
{
for(int i=0;i<dotNumber;i++) cout<<a[i].vertex<<" ";
}
void Picture::outputTable()
{
ArcNode *p;
for(int i=0;i<dotNumber;i++)
{
p=a[i].firstedge;
cout<<a[i].vertex<<" ";
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}

}
void Picture::DFSTraverse(int v)
{
cout<<a[v].vertex<<" "; visited[v]=true;
ArcNode *p;
p=a[v].firstedge;
while(p!=NULL)
{
int j=p->data;
if(visited[j]==false)
{
DFSTraverse(j);

p=p->next;
}
}
void Picture::BFSTraverse(int v)
{
int q[MaxSize];
int front=-1,rear=-1;
cout<<a[v].vertex<<" ";
visited[v]=true;
q[++rear]=v;
while(front!=rear)
{
v=q[++front];
ArcNode *p=a[v].firstedge;
while(p!=NULL)
{
int j=p->data;

if(visited[j]==false)
{
cout<<a[j].vertex<<" ";
visited[j]=true;
q[++rear]=j;
}
p=p->next;
}
}
 } 
int main()
{
Picture *a=new Picture();
a->outputDot();
cout<<endl;
a->outputTable();
for(int i=0;i<a->getdotNumber();i++)
{
if(a->visited[i]==false)
a->DFSTraverse(i);
}

cout<<endl;
a->renovate();
for(int i=0;i<a->getdotNumber();i++)
{
if(a->visited[i]==false)
a->BFSTraverse(i);
}

return 0;
 } 
/*
5 3
A B C D E
0 1
0 2
0 3




*/