1. 程式人生 > >實驗六 圖的實驗1

實驗六 圖的實驗1

#include<iostream.h>
const int Maxsize=6;
const int Maxedge=6;
int visited[Maxsize]={0};

struct ArcNode
{
	int adjvex;
	ArcNode*nextarc;
};

struct Vnode
{
	int v;
	ArcNode*next;
}a[Maxsize+1];

void creategraph()
{
	int i,j,k;
	ArcNode*s;
	for(i=1;i<=Maxsize;i++)
	{
		a[i].v=i;
		a[i].next=NULL;
	}
	for(k=1;k<=Maxedge;k++)
	{
		cout<<"請輸入第"<<k<<"條邊的兩個頂點的序號:";
		cin>>i>>j;
		if(i>9||i<0||j<0||j>9)
		{
			cout<<"error!!"<<endl<<endl;
			break;
		}
		else
		{
			cout<<endl;
		    s=new ArcNode;
		    s->adjvex=j;
		    s->nextarc=a[i].next;
		    a[i].next=s;
		    s=new ArcNode;
		    s->adjvex=i;
		    s->nextarc=a[j].next;
		    a[j].next=s;
		}
	}
}

void display()
{
	ArcNode*p;
	cout<<"建立的圖為:"<<endl;
	for(int i=1;i<=Maxsize;i++)
	{
		p=a[i].next;
		cout<<a[i].v<<"->";
		while(p->nextarc!=NULL)
		{
			cout<<p->adjvex<<"->";
			p=p->nextarc;
		}
		cout<<p->adjvex<<endl;
	}
}

class MGraph
{
	public:
		MGraph(char a[],int n,int e);
		~MGraph(){}
		void DFSTraverse(int v);
		void BFSTraverse(int v);
	private:
		char vertex[Maxsize];
		int arc[Maxsize][Maxsize];
		int vertexNum,arcNum;
};

MGraph::MGraph(char a[],int n,int e)
{
	int i,j,k;
	vertexNum=n;
	arcNum=e;
	for(i=0;i<5;i++)
		vertex[i]=a[i];
	for(i=0;i<5;i++)
		for(j=0;j<5;j++)
			arc[i][j]=0;
		for(k=0;k<5;k++)
		{
			cout<<"請輸入邊的兩個頂點的序號:";
			cin>>i>>j;
			arc[i][j]=1;
			arc[j][i]=1;
		}
}

void MGraph::DFSTraverse(int v)
{
	cout<<vertex[v];visited[v]=1;
	for(int j=0;j<vertexNum;j++)
		if(arc[v][j]==1&&visited[j]==0)
			DFSTraverse(j);
}

void MGraph::BFSTraverse(int v)
{
	int Q[Maxsize];
	int front=-1,rear=-1;
	cout<<vertex[v];
	visited[v]=1;
	Q[++rear]=v;
	while(front!=rear)
	{
		v=Q[++front];
		for(int j=0;j<vertexNum;j++)
			if(arc[v][j]==1&&visited[j]==0)
			{
				cout<<vertex[j];
				visited[j]=1;
				Q[++rear]=j;
			}
	}
}


int main()
{
	cout<<"鄰接矩陣的深度優先遍歷和廣度優先遍歷"<<endl;
	char ch[]={'A','B','C','D','E'};
	MGraph MG(ch,5,5);
	for(int i=0;i<Maxsize;i++)
		visited[i]=0;
	cout<<"深度優先遍歷序列:"<<endl;
	MG.DFSTraverse(0);
	cout<<endl;
	for(i=0;i<Maxsize;i++)
		visited[i]=0;
	cout<<"廣度優先遍歷序列:"<<endl;
	MG.BFSTraverse(0);
	cout<<endl<<endl<<endl;
    cout<<"鄰接表輸出鄰接點"<<endl;
	char yn='y';
	int k;
	creategraph();
	display();
	return 0;
}