C++数据结构,判断图中是否存在边x,y

判断图中是否存在边<x,y>

更多内容请访问个人主页

1. 存储结构为邻接表时

typedef char VertexType;
typedef int EdgeType;
typedef struct
{
	VertexType Vex[MAXSIZE];   //点表
	EdgeType Edge[MAXSIZE][MAXSIZE];  //边表
}MGraph;

1.算法描述:首先在点表里查找是否存在顶点x和顶点y。若不存在,则说明不存在<x,y>;若存在,则返回x,y的下标。其次,根据x,y的下标查找边表。判断其值是否为1(存在),否则不存在。
2.伪代码:

bool Adjacent(MGraph G, VertexType x, VertexType y)
{
	int i = 0;
	int tag1 = 0, tag2 = 0;  // 标志, 如果tag = 0说明不存在该点
	int idx1, idx2;    //记录x,y的下标
	while (G.Vex[i] != '\0')
	{
		if (x == G.Vex[i])   //如果找到x修改tag1并返回下标
		{
			tag1 = 1; idx1 = i;   
			i++;
		}
		else if (y == G.Vex[i])   //如果找到y修改tag2并返回下标
		{
			tag2 = 1; idx2 = i;
			i++;
		}
		else
			i++;
	}
	if (!(tag1 == 1 && tag2 == 1))   //点表不存在其中一个顶点,返回false
		return false;
	if (G.Edge[idx1][idx2] == 1 || G.Edge[idx2][idx1] == 1)  //有向图不对称
		return true;
	else
		return false;
}

2. 存储结构为邻接表时


typedef char VertexType;
typedef struct ArcNode  //边表
{
	int adjvex;
	struct ArcNode* next;
}ArcNode;
typedef struct VNode   //点表
{
	VertexType data;
	ArcNode* first;
}VNode,AdjList[MAXSIZE];
typedef struct
{
	AdjList vertices;   //邻接表
	int vexnum, arcnum;
}ALGraph;

bool Adjacent(ALGraph G, VertexType x, VertexType y)
{
	int i = 1;
	int tag1 = 0, tag2 = 0;
	int idx1, idx2;
	while (G.vertices[i].data != ' ')
	{
		if (x == G.vertices[i].data)
		{
			tag1 = 1; idx1 = i;
			i++;
		}
		else if (y == G.vertices[i].data)
		{
			tag2 = 1; idx2 = i;
			i++;
		}
		else
			i++;
	}
	if (!(tag1 == 1 && tag2 == 1))
		return false;
	ArcNode* p = G.vertices[idx1].first->next;   //指向x链接的边表的第一个顶点
	ArcNode* q = G.vertices[idx2].first->next;   //指向y链接的边表的第一个顶点
	//边表加入了一个头结点便于操作 所有有个->next
	while (p != NULL)
	{
		if (p->adjvex == idx2)   //如果找到下标说明存在边
			return true;
		p = p->next;
	}
	while (q != NULL)
	{
		if (q->adjvex == idx1)
			return true;
		q = q->next;
	}
	return false;
}
发布了16 篇原创文章 · 获赞 25 · 访问量 1146

猜你喜欢

转载自blog.csdn.net/weixin_41546300/article/details/102959848