圖的數組表示法node
藉助一個二維數組表示圖,該二維數組的第i行,第j列的值表示從Node[i]到Node[j]:數組
無向圖(網):是否有邊 / 權值,arr[i][j] == arr[j][i],無向圖(網)的特性,矩陣關於對角線對稱。
spa
有向圖(網):是否有弧 / 權值。code
//圖的數組表示法 //最大頂點個數 const int MAX_VERTEX = 100; //最大值 const int MAX_VALUE = (1 << 31) - 1; typedef struct _tagArcCell { int adj; //無向網,權值 char character; //頂點信息,字符 }ArcCell, ArcCell_ARRAY[MAX_VERTEX][MAX_VERTEX]; typedef struct _tagGraph { char vexs[MAX_VERTEX]; //頂點向量 ArcCell_ARRAY arcCellArray; //節點數組 int nodeNum; //頂點數 int edgeNum; //邊數 }Graph;
//根據點,獲取該點在圖中的位置 int Locate(Graph& graph, char ch) { for (int i = 0; i < graph.nodeNum; ++ i) { if (ch == graph.vexs[i]) { return i; } } return -1; }
void CreateGraph(Graph& graph) { //初始化無向網的值 int num = 0; cout << "請輸入圖的頂點個數"; cin >> num; graph.nodeNum = num; cout << "請輸入圖的邊數"; cin >> num; graph.edgeNum = num; cout << endl<<endl; cout<<"下面開始構造頂點向量"<<endl; for (int i = 0; i < graph.nodeNum; ++ i) { cout << "請輸入每一個頂點:"; char ch = 0; cin >> ch; graph.vexs[i] = ch; } cout << "\r\n頂點向量構造完畢\r\n\r\n"; cout << "下面開始初始化鄰接矩陣\r\n"; for (int i = 0; i < graph.nodeNum; ++ i) { for (int j = 0; j < graph.nodeNum; ++ j) { graph.arcCellArray[i][j].adj = MAX_VALUE; } } cout << "\r\n鄰接矩陣初始化完畢\r\n\r\n"; cout << "下面開始構造邊,併爲邊分配權值\r\n"; for (int i = 0; i < graph.edgeNum; ++ i) { cout << "請先輸入一個頂點:"; char ch = 0; cin >> ch; int nFrom = Locate(graph, ch); if (-1 == nFrom) { cout << "您輸入的頂點不在此圖上,請從新輸入\r\n"; -- i; continue; } cout << "請輸入另外一個頂點:"; cin >> ch; int nTo = Locate(graph, ch); if (-1 == nTo) { cout << "您輸入的頂點不在此圖上,請從新輸入本條邊\r\n"; -- i; continue; } int adj = 0; cout << "請輸入該邊的權值:"; cin >> adj; graph.arcCellArray[nFrom][nTo].adj = graph.arcCellArray[nTo][nFrom].adj = adj; } cout <<endl<< "構造邊和權值結束"<<endl<<endl; }
int _tmain(int argc, _TCHAR* argv[]) { Graph graph; CreateGraph(graph); return 0; }