資源描述:
《鄰接矩陣實(shí)現(xiàn)無(wú)向圖有向圖基本操作》由會(huì)員上傳分享,免費(fèi)在線(xiàn)閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、鄰接矩陣實(shí)現(xiàn)無(wú)向圖有向圖基本操作/*//*以無(wú)向圖為基類(lèi),有向圖為派生類(lèi),以鄰接矩陣為存儲(chǔ)方式,實(shí)現(xiàn)無(wú)向圖,有向圖的建立,插入,刪除等操作*//*/#includeiostream#includestringusingnamespacestd;struct_ArcInfo//邊信息{char*v1;char*v2;};struct_VexInfo{intadj;//頂點(diǎn)類(lèi)型,是否相鄰接};classUnDirectGraph{public:intArcNum;//邊數(shù)_ArcInfoArcInfo;_Ve
2、xInfoAdjMax[20][20];//鄰接矩陣intVexNum;//頂點(diǎn)數(shù)char*Vexs[20];//存放頂點(diǎn)public:UnDirectGraph();~UnDirectGraph();intLocateVex(char*Vex);//獲得節(jié)點(diǎn)在圖中序號(hào),在鄰接矩陣中使用virtualvoidCreateGraph();//構(gòu)造無(wú)向圖voidShowGraph();//輸出鄰接矩陣voidInsertVex(char*&newVex);//向無(wú)向圖中插入一個(gè)新節(jié)點(diǎn)virtualvoidIn
3、sertArc(char*&v1,char*&v2);//向無(wú)向圖中插入一條邊virtualvoidDeleteVex(char*oldVex);//刪除一個(gè)節(jié)點(diǎn)virtualvoidDeleteArc(char*&v1,char*&v2);//刪除一條邊};classDirectGraph:publicUnDirectGraph//有向圖繼承無(wú)向圖{public:DirectGraph();~DirectGraph();//重寫(xiě)基類(lèi)的四個(gè)函數(shù),基類(lèi)中相應(yīng)函數(shù)設(shè)為虛函數(shù)voidCreateGraph();
4、//構(gòu)造有向圖voidInsertArc(char*&v1,char*&v2);//向有向圖中插入一條弧voidDeleteArc(char*&v1,char*&v2);//刪除有向圖中一條弧voidDeleteVex(char*oldVex);//刪除有向圖中的一個(gè)頂點(diǎn)};UnDirectGraph:UnDirectGraph(){VexNum=0;ArcNum=0;inti;for(i=0;i20;i++)Vexs[i]=newchar;ArcInfo.v1=newchar;ArcInfo.v2=ne
5、wchar;}UnDirectGraph:~UnDirectGraph(){}intUnDirectGraph:LocateVex(char*Vex)//獲取節(jié)點(diǎn)vex在圖中的位置{inti;for(i=0;iVexNum;i++){if(strcmp(Vex,Vexs[i])==0)returni;}return0;}voidUnDirectGraph:CreateGraph()//創(chuàng)建無(wú)向圖{cout"輸入頂點(diǎn)數(shù)和邊數(shù):";cinVexNumArcNum;inti,j,k;cout"輸入各個(gè)頂點(diǎn):"e
6、ndl;for(i=0;iVexNum;i++)//輸入頂點(diǎn)cinVexs[i];for(i=0;iVexNum;i++){for(j=0;jVexNum;j++)AdjMax[i][j].adj=0;//鄰接矩陣初始化各點(diǎn)不相鄰}for(k=0;kArcNum;k++){cout"輸入邊的信息:";cinArcInfo.v1ArcInfo.v2;i=LocateVex(ArcInfo.v1);j=LocateVex(ArcInfo.v2);AdjMax[j][i].adj=AdjMax[i][j].ad
7、j=1;//無(wú)向圖中兩個(gè)頂點(diǎn)相鄰}}voidUnDirectGraph:ShowGraph()//輸出鄰接矩陣{inti,j;for(i=0;iVexNum;i++){for(j=0;jVexNum;j++)cout""AdjMax[i][j].adj;coutendl;}}voidUnDirectGraph:InsertVex(char*&newVex)//向圖中插入一個(gè)節(jié)點(diǎn){Vexs[VexNum]=newVex;VexNum++;for(inti=0;iVexNum;i++){AdjMax[i][V
8、exNum-1].adj=AdjMax[VexNum-1][i].adj=0;//插入一個(gè)孤立節(jié)點(diǎn)}}voidUnDirectGraph:InsertArc(char*&v1,char*&v2)//在圖中增加一條邊{inti,j;i=LocateVex(v1);j=LocateVex(v2);if(i0
9、
10、j0)return;ArcNum++;AdjMax[i][j].adj=AdjMax[j][i].adj=1;}voidU