鄰接矩陣及鄰接表
#include <iostream>
#include "stdio.h"
#include "stdlib.h"
#include "cstdlib"//syste()函式需要該標頭檔案;
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
//#define MaxInt 32767 //網中表示極大值,即∞,若為無向圖,Mxint 0;
#define INFINITY 0//圖中表示初始值0;網中表示極大值,即∞,這個單單詞比Maxint含義好
#define MVNum 100 //最大頂點數
//00定義 點 邊 圖網
typedef char VerTexType; //假設頂點的資料型別為字元型
typedef int ArcType; //假設邊的權值型別為整型,若為無向圖,ArcType->EdgeType
typedef struct{
VerTexType vexs[MVNum]; //頂點表
ArcType arcs[MVNum][MVNum]; //鄰接矩陣
int vexnum,arcnum; //圖的當前點數和邊數
}AMGraph;
//01 定位Locate the vertex you need
int LocateVex(AMGraph G,char ch)
{
int i=0;
for(i=0; i<G.vexnum;i++)
{
if(G.vexs[i]==ch)
break;
}
if(i>=G.vexnum) //如果超過頂點數量了,返回-1
return -1;
return i; //return the index of the vertex you are looking
}
//02 列印 頂點(一維陣列) 邊(二維陣列)
Status PrintAMGraphVex
{
int i;
printf("你輸入的頂點是:");
for(i=0;i<G.vexnum;i++)
{
printf("%c\t",G.vexs[i]);
}
printf("\n");
return OK;
}
Status PrintAMGraphArc(AMGraph G)//列印鄰接矩陣,二維陣列
{
int i,j;
cout<<"當前鄰接矩陣是:"<<endl;
for(i=0;i<G.vexnum;i++)
{
for(j=0;j<G.vexnum;j++)
{
printf("%d\t",G.arcs[i][j]);
}
printf("\n\n\n");
}
return OK;
}
//03 建立一個無方向網圖的鄰接矩陣表示
Status CreateGraph(AMGraph &G)
{
int i,j,k,w;
char v1,v2;
printf("Input the number of vertex and arc:\n");
cin>>G.vexnum>>G.arcnum;
printf("The number is %d and %d.\n",G.vexnum,G.arcnum);//驗證輸入內容
//initialize vertex arcs;
printf("Input %d vertex: ",G.vexnum);
for(i=0;i<G.vexnum;++i)
cin>>G.vexs[i];
PrintAMGraphVex(G);//驗證輸入的頂點
for(i=0;i<G.vexnum;++i)
for(j=0;j<G.vexnum;++j)
G.arcs[i][j]=INFINITY;//0
PrintAMGraphArc(G);//驗證輸入的邊
for (k = 0; k < G.arcnum; ++k)
{
printf("input the i and j of (Vi,Vj), and the weight:\n"); //一條邊的兩個結點,和這條邊的權重,無向圖權值輸入1;也可以前面宣告為1.
cin>>v1>>v2>>w;
//cout<<"你輸入的v1 v2 w :"<<v1<<v2<<w<<endl;
i=LocateVex(G,v1);
j=LocateVex(G,v2);
//cout<<"i:"<<i<<" ";
//cout<<"j:"<<j<<endl;
if(i==-1 || j==-1)
{
return ERROR;
}
G.arcs[i][j]=w;
G.arcs[j][i]=G.arcs[i][j];//如果是有向網,可以w1 w2
//cout<<"G.arcs[i][j] :"<<G.arcs[i][j]<<endl;
}
return OK;
}
Status main()
{
AMGraph G;
CreateGraph(G);
PrintAMGraphArc(G);
system("pause");
return OK;
}