图的基本概念及其公式
创建邻接表
typedef struct ADNode {
int adjves; //该边的邻接点编号
struct ADNode* nexttarc; //指向下一条边的指针
int weight; //该边的相关信息
}ArcNode; //边结点的类型
typedef struct Vnode {
char info; //顶点的其他信息
ArcNode* firstarc; //指向第一个边节点
}VNode; //邻接表的头节点类型
typedef VNode AdjList[MAXV]; //邻接表的头节点数组
typedef struct {
AdjList adjList;
int n, e; //邻接表的顶点数n和边数e
}AdjGraph;
void GreatAdj(AdjGraph*& G, int A[][MAXV], int n) { //创建邻接表
int i, j; ArcNode* p;
G->e = 0;
G = (AdjGraph*)malloc(sizeof(AdjGraph));
for(int i=0;i<n;i++)
for(j=n-1;j>=0;j--)
if (A[i][j] != 0)
{
p = (ArcNode*)malloc(sizeof(ArcNode));
p->adjves = j;
p->weight = A[i][j];
p->nexttarc = G->adjList[i].firstarc;
G->adjList[i].firstarc = p;
G->e++;
}
输出邻接表
void DispAdj(AdjGraph* G) { //输出邻接表
int i; ArcNode* p;
for (i = 0; i < G->n; i++) {
p = G->adjList[i].firstarc;
printf("%3d", i);
while (p != NULL) {
printf("%3d[%d]->", p->adjves, p->weight);
p = p->nexttarc;
}
printf("\n");
}
}
创建邻接矩阵
typedef struct { //邻接矩阵算法
int no; //顶点编号
char info; //顶点其他信息
}VertexType;
typedef struct {
int edges[MAXV][MAXV]; //邻接矩阵
int n, e;
VertexType vexs[MAXV]; //存放顶点信息
}MatGraph;
采用DFS算法深度优先遍历
void DFS(AdjGraph* G, int v) { //深度优先遍历
ArcNode* p;
visited[v] = 1;
printf("%d", v);
p = G->adjList[v].firstarc;
while (p != NULL) {
if (visited[p->adjves] == 0)
DFS(G, p->adjves);
p = p->nexttarc;
}
}
BFS采用广度优先算法遍历
typedef struct {//创建队列
int data[MAXV];
int front , rear;
}SqQueue;
void InitQueue(SqQueue*& q) { //初始化队列
q = (SqQueue*)malloc(sizeof(SqQueue));
q->front = q->rear = 0;
}
bool QueueEmpty(SqQueue* q) { //判断队列是否为空
return(q->front = q->rear);
}
bool enQueue(SqQueue*& q, int e) { //进队列
if (q->rear == MAXV - 1)
return false;
q->rear++;
q->data[q->rear] = e;
return true;
}
bool deQueue(SqQueue*& q, int& e) { //出队列
if (q->front = q->rear)
return false;
q->front++;
e = q->data[q->front];
return true;
}
void BFS(AdjGraph* G, int v) { //广度优先算法
int w, i; ArcNode* p;
SqQueue* qu;
InitQueue(qu);
int visited[MAXV];
for (i = 0; i < G->n; i++)visited[i] = 0;
printf("%2d", v);
visited[v] = 1;
enQueue(qu, v);
while (!QueueEmpty(qu)) {
deQueue(qu, w);
p = G->adjList[w].firstarc;
while (p != NULL) {
if (visited[p->adjves] == 0)
{
printf("%2d", p->adjves);
visited[p->adjves] = 1;
enQueue(qu, p->adjves);
}
p = p->nexttarc;
}
}
printf("\n");
}

被折叠的 条评论
为什么被折叠?



