图:一种新的非线性数据结构,在图结构中,数据元素之间的关系是多对多的,即如果任选一个结点作为初始结点,则途中任意一个结点有多个前驱结点和多个后继结点。
两种图:
(1)有向图:
n个结点的图中
有n(n-1)条边,任意两个节点之间有方向相反的两条边,则称此图为有向完全图
(2)无向图
n个结点的图中
有n(n-1)/2条边,任意两个结点之间有且只有一条边,则称此图为无向完全图。
自己的实现代码,因为只是为了实现图,很多别的操作没做,但是大抵图的实现是成功的,比较仓促的写的,但是对于图的构造还是成功了
主函数
#include "SeqList.h"
#include <iostream>
using namespace std;
typedef struct RowCol
{
int row;
int col;
int weight;
}RowColWeight;
#define MaxVertices 10
#define MaxWeight 10000
#include "Matrix.h"
void CreateGraph(AdjMGraph* G, char *a, RowColWeight rew[],int num)
{
int i = 0;
for (a[i]; a[i] != '\0'; ++i)
{
InsertVertices(G,a[i]);
}
for (int j = 0; j < num; ++j)
{
InsertMartrix(rew[j].row, rew[j].col, G, rew[j].weight);
}
}
int main()
{
AdjMGraph graph;
Initiate(&graph, 5);
char a[] = "ABCDE";
RowColWeight rew[] = { {0,1,2},{0,4,20},{1,3,20},{2,1,40},{3,2,50} };
CreateGraph(&graph, a, rew,5);
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
cout << graph.edge[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < 5; ++i)
{
cout << graph.Vertices.list[i].data << " ";
}
cout << endl;
return 0;
}
SeqList.h
#pragma once
typedef struct Adj
{
int dest;
Adj* next;
}adj;
typedef struct ListNode
{
char data;
int socre;
adj* next;
}Node;
typedef struct List
{
Node list[10];
int size;
}List;
void initList(List* l);
int Insert(char data,List *l);
SeqList.cpp
#include "SeqList.h"
void initList(List* l)
{
l->size = 0;
}
int Insert(char data, List *l)
{
if (l->size >= 10)
{
return 0;
}
else
{
l->list[l->size].data = data;
l->list[l->size].socre = l->size;
l->size++;
}
}
Matrix.h
#pragma once
#include "SeqList.h"
typedef struct
{
List Vertices;//存放结点的顺序表
int edge[MaxVertices][MaxVertices];//存放边的邻接矩阵
int numOfEdges;//边的条数
}AdjMGraph;
void Initiate(AdjMGraph *G, int n)
{
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (i == j)
{
G->edge[i][j] = 0;
}
else
{
G->edge[i][j] = MaxWeight;
}
}
}
G->numOfEdges = 0;
initList(&G->Vertices);
}
void InsertVertices(AdjMGraph* G, char data)
{
Insert(data, &G->Vertices);
}
void InsertMartrix(int row,int col,AdjMGraph* G,int weight)
{
//不做参数检查了,我就是实现一下图
G->edge[row][col] = weight;
G->numOfEdges++;
}