圖的基本操作實現
阿新 • • 發佈:2018-12-02
#include<iostream> using namespace std; const int MaxSize=10; class MGraph { char vertex[MaxSize]; int arc[MaxSize][MaxSize]; int vertexNum,arcNum; public: MGraph(char a[],int n,int e); ~MGraph(){} void DF(int v,int visited[]); void BF(int v,int visited[]); }; MGraph::MGraph(char a[],int n,int e) { vertexNum=n;arcNum=e; for(int i=0;i<vertexNum;i++) vertex[i]=a[i]; for(int q=0;q<vertexNum;q++) for(int b=0;b<vertexNum;b++) arc[q][b]=0; int z,x; for(int c=0;c<arcNum;c++) { cout<<"input:"; cin>>z>>x; arc[z][x]=1; arc[x][z]=1; } } void MGraph::DF(int v,int visited[]) { cout<<vertex[v]; visited[v]=1; for(int j=0;j<vertexNum;j++) if(arc[v][j]==1&&visited[j]==0) DF(j,visited); } void MGraph::BF(int v,int visited[]) { 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() { char ch[]={'A','B','C','D','E'}; int visited[MaxSize]; for(int i=0;i<MaxSize;i++) visited[i]=0; MGraph MG(ch,5,6); cout<<"DF"<<endl; MG.DF(0,visited); for(int a=0;a<MaxSize;a++) visited[a]=0; cout<<endl<<"BF"<<endl; MG.BF(0,visited); cout<<endl; return 0; }