C++ 圖的鄰接錶轉鄰接矩陣表示
阿新 • • 發佈:2019-01-14
#include <bits/stdc++.h> #define MaxSize 100 /* * Created by HarvestWu on 2018/07/20. */ using namespace std; typedef int ElemType; //鄰接矩陣頂點型別 typedef struct VertexType { int no; //頂點編號 char info; }VertexType; //圖的鄰接矩陣型別 typedef struct MGraph { int edges[MaxSize][MaxSize]; int n, e; //頂點數、邊數 VertexType vex[MaxSize];//存放結點資訊 }MGraph; //邊表 typedef struct ArcNode { int adjvex; //該邊所指向的結點的位置 struct ArcNode *nextarc; //指向下一條邊的指標 int info; // }ArcNode; //頂點表 typedef struct { char data; //頂點資訊 ArcNode *firstarc; //指向第一條邊的指標 }VNode; //鄰接表 typedef struct { VNode adjlist[MaxSize]; int n, e; //頂點數、邊數 }AGraph; //圖的鄰接表型別 //建立有向圖的鄰接表 void createAGraph(AGraph *&AG) { int i, j, k; ArcNode *q; cout << "輸入頂點數、邊數:" << endl; cin >> AG->n >> AG->e; for (i = 0; i<AG->n; i++) { AG->adjlist[i].data = i; AG->adjlist[i].firstarc = NULL; } cout << "輸入邊(vi,vj)的頂點序號i,j:" << endl; for (k = 0; k<AG->e; ++k) { cin >> i >> j; //頭插法 q = (ArcNode*)malloc(sizeof(ArcNode)); q->adjvex = j; q->nextarc = AG->adjlist[i].firstarc; AG->adjlist[i].firstarc = q; } } //圖的鄰接錶轉鄰接矩陣表示 void MGraphToAGraph(MGraph &g1, AGraph *g2) { ArcNode *p; g1.n = g2->n; for (int i = 0; i < g1.n; ++i) for (int j = 0; j < g1.n; ++j) g1.edges[i][j] = 0; for (int i = 0; i < g2->n; ++i) { p = g2->adjlist[i].firstarc; while (p) { g1.edges[i][p->adjvex-1] = 1; p = p->nextarc; } } } //列印圖的鄰接矩陣 void Visit(MGraph g1) { for (int i = 0; i < g1.n; i++) { for (int j = 0; j < g1.n; j++) cout << g1.edges[i][j] << " "; cout << endl; } } int main() { AGraph *AG; MGraph MG; AG = (AGraph*)malloc(sizeof(AGraph)); createAGraph(AG); MGraphToAGraph(MG, AG); Visit(MG); return 0; }