1. 程式人生 > >判斷兩個頂點之間是否聯通,是否有長度為K的路徑

判斷兩個頂點之間是否聯通,是否有長度為K的路徑

最近學習了圖,下面是關於圖的遍歷幾個栗子

#include "iostream"
#define MAXSIZE 4
using namespace std;

struct ArcNode//邊表 
{    
	int adjvex;
 	ArcNode *next;
};

struct VertexNode //頂點表 
{
	int vertex;
 	ArcNode *firstedge;
};

VertexNode *V = new VertexNode[MAXSIZE];
int visited[MAXSIZE];

//5.判斷a頂點是否有路徑到 b頂點
/**********************************************************/
bool Ergodic_Vertex(int a,int b)//返回1表示有路徑能到達 (起點,終點)
{
	ArcNode *p;
	visited[a]=1;
	if(V[a].vertex == V[b].vertex)	return 1;
	else
	{
		p=V[a].firstedge;
		while(p!=NULL)
		{
			int temp = p->adjvex;
			if(visited[temp]==0)	
			{
				if(Ergodic_Vertex(temp,b))
					return 1;	
			}
			p=p->next;
		}
	}
	
}
/*******************************************************/


//8.判斷a頂點是否有長度為k的路徑到 b頂點
/*******************************************************/

void Ergodic_Vertex(int a,int b,int k,int K,int *v)//輸出幾個OK表示有幾條 (起點,終點,路徑長度,0,結點陣列)
{
	int KK=K;
	int visite[MAXSIZE];
	for(int i=0;i<MAXSIZE;i++)
	{
		visite[i] = v[i];
	}
	ArcNode *p;
	visite[a]=1;
		p=V[a].firstedge;	
		KK=KK+1;	
		while(p->adjvex!=-1)
		{
			int temp = p->adjvex;      
			if(visite[temp]==0)	
			{
				if ((k == KK) && (temp==b))//去掉+1 
				{
					cout<<"OK!"<<endl;
				}
				Ergodic_Vertex(temp,b,k,KK,visite);//去掉+1 
			}
			p=p->next;
		}                          	
}
/*******************************************************/

void build()//鄰接表建立圖 
{
	ArcNode *p=NULL;
	ArcNode *p2=NULL;
	int temp;
	cout<<"以0結束"<<endl;
	for(int i=0;i<4;i++)
	{
		p=V[i].firstedge = new ArcNode;
		cout<<i+1<<"周圍的頂點為:"<<endl;
		cin>> temp;
		p->adjvex = temp-1;
		if(p->adjvex == -1)
		{
			V[i].firstedge=NULL;
		}
		while(p->adjvex!=-1)
		{
			p2 = new ArcNode;
			cout<<i+1<<"周圍的頂點為:"<<endl;
			cin>> temp;
			p2->adjvex=temp-1;
			p->next = p2;
			p=p2;						
		}
		system("cls");
		cout<<"以0結束"<<endl;
		
	}
	cout<<"構建完成"<<endl;
}

void clear_V()//初始化 
{
	for(int i = 0;i < 5; i++)
	{
		V[i].vertex = i+1;
	}
}