#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define MAX_VERTEX_NUM 20
typedef int Status;
typedef char VertexType;
typedef struct ArcNode{
//弧信息的结构
int adjvex; //弧所连接的顶点的位置信息
struct ArcNode *nextarc; //指向下一条弧
}ArcNode;
typedef struct VNode{
//顶点的信息的结构
VertexType data; //顶点存放的数据(类型)
ArcNode *firstarc; //指向第一个依附在该顶点的弧的指针
}VNode, AdjList[MAX_VERTEX_NUM];
typedef struct{
//图的结构
AdjList vertices; //每一个顶点的链表
int vexnum, arcnum; //图顶点的个数,弧的条数
}ALGraph;
int visited[MAX_VERTEX_NUM];
int count;
int low[MAX_VERTEX_NUM];
int LocateVex(ALGraph A, char v){
//求出顶点在顶点矩阵的位置,也就是得出V是几号顶点;
for(int i=0; i<A.arcnum; i++)
if(A.vertices[i].data == v)
return i;
}
void Print(ALGraph A){
//输出邻接链表
int i;
ArcNode *p;
printf("邻接表为:\n");
for(i=0; i<A.vexnum; i++){
p = A.vertices[i].firstarc;
printf("%c -- ", A.vertices[i].data);
while(p){
printf("%c", A.vertices[p->adjvex].data);
p = p->nextarc;
if(p) printf(" - ");
}
printf("\n");
}
}
Status CreateUDG(ALGraph &A){
//采用邻接链表的存储格式存储无向图
ArcNode *s;
int i, j, k;
char v[2];
printf("输入顶点数,弧数:");
scanf("%d %d", &A.vexnum, &A.arcnum);
printf("输入各顶点的值:");
for(i=0; i<A.vexnum; i++){
scanf("%s", &A.vertices[i].data);
A.vertices[i].firstarc = NULL;
}
for(j=0; j<A.arcnum; j++){
printf("输入两个连接的顶点:");
for(i=0; i<2; i++) scanf("%s", &v[i]);
i = LocateVex(A, v[0]); k = LocateVex(A, v[1]);
s = (ArcNode*)malloc(sizeof(ArcNode));
s->adjvex = i;
s->nextarc = A.vertices[k].firstarc;
A.vertices[k].firstarc = s;
//反向
s = (ArcNode*)malloc(sizeof(ArcNode));
s->adjvex = k;
s->nextarc = A.vertices[i].firstarc;
A.vertices[i].firstarc = s;
}
}
void DFSArticul(ALGraph A, int v0){
//查找关节点
int min, w;
ArcNode *p;
visited[v0] = min = ++count;
for(p=A.vertices[v0].firstarc; p; p=p->nextarc){
w = p->adjvex;
if(visited[w] == 0){
DFSArticul(A, w);
if(low[w]<min) min = low[w];
if(low[w]>=visited[v0]);
printf("第 %d 个位置的 %c 元素为关节点\n", v0+1, A.vertices[v0].data);
}
else if(visited[w]<min) min = visited[w];
}
low[v0] = min;
}
void FindArticul(ALGraph A){
int v, i;
ArcNode *p;
count = 1; low[0] = visited[0] = 1;
for(i=1; i<A.vexnum; i++) visited[i] = 0;
p = A.vertices[0].firstarc;
v = p->adjvex;
DFSArticul(A, v);
if(count<A.vexnum){
printf("第 %d 个位置的 %c 元素为关节点\n", 1, A.vertices[0].data);
while(p->nextarc){
p = p->nextarc; v = p->adjvex;
if(visited[v] == 0) DFSArticul(A, v);
}
}
}
int main(){
ALGraph A;
CreateUDG(A);
Print(A);
FindArticul(A);
}
连通图的关节点
最新推荐文章于 2021-11-03 18:50:16 发布