图的定义和术语
完全图:任意两个点都有一条边相连
连通图(强连通图)
连通分量(强连通分量)
有向图和无向图的工程案例
#include "pch.h" #include <iostream> using namespace std; //有向图 无向图 有向网 无向网 enum GraphKing { DG, DN, UDG, UDN }; //定义图 typedef struct Node { int *vex; //顶点个数 int vexnum; //顶点数 int edge; //图的边数 int **adjmatrix;//图的邻接矩阵 GraphKing kind; //图的类型 }Mygraph; //创建图 void CreateGraph(Mygraph &g,GraphKing king) { cout << "请输入图的顶点个数:"; cin >> g.vexnum; cout << "请输入图的边的条数:"; cin >> g.edge; g.kind = king;//确认创建图的类型 //开辟空间 g.vex = new int[g.vexnum]; g.adjmatrix = new int*[g.vexnum]; cout << "输出顶点个数:" << g.vexnum << endl; //给邻接矩阵申请空间 for (int i = 0; i < g.vexnum; i++) { g.adjmatrix[i] = new int[g.vexnum]; } //给邻接矩阵初始化 for (int j = 0; j < g.vexnum; j++) { for (int k = 0; k < g.vexnum; k++) { if (g.kind==DG||g.kind==DN) { g.adjmatrix[j][k] = 0; } else { g.adjmatrix[j][k] = INT_MAX; } } } //输入图的顶点 cout << "请输入两个顶点的序号(1,2分别代表1号顶点和2号顶点):" << endl;; for (int i = 0; i < g.edge; i++) { int a, b; cout << "请依次输入图(vi, vj)的vi和vj:"; cin >> a >> b; //无向图 if (g.kind==DN) { g.adjmatrix[b - 1][a - 1] = 1; g.adjmatrix[a - 1][b - 1] = 1; } //有向图 else if (g.kind==DG) { g.adjmatrix[a - 1][b - 1] = 1; } //有向网 else if (g.kind==UDG) { int weight; cout << "请输入该边的权:"; cin >> weight; g.adjmatrix[a - 1][b - 1] = weight; } else if (g.kind == UDN) { int weight; cout << "请输入该边的权:"; cin >> weight; g.adjmatrix[a - 1][b - 1] = weight; g.adjmatrix[a - 1][b - 1] = weight; } } } //输出图 void PrintGraph(Mygraph g) { for (int i = 0; i <g.vexnum; i++) { for (int j = 0; j < g.vexnum; j++) { //有/无向网 if (g.adjmatrix[i][j]==INT_MAX) { cout << "∞" << endl; } else { cout << g.adjmatrix[i][j] << " "; } } cout << endl; } } //清除图 void ClearGraph(Mygraph g) { delete g.vex; g.vex = NULL; for (int i = 0; i < g.vexnum; i++) { delete g.adjmatrix[i]; g.adjmatrix[i] = NULL; } delete g.adjmatrix; } int main() { Mygraph g; cout << "有向图案例:" << endl; CreateGraph(g, DG); PrintGraph(g); ClearGraph(g); cout << endl; cout << "无向图案例:" << endl; CreateGraph(g, DN); PrintGraph(g); ClearGraph(g); cout << endl; return 0; }
结果为: