图的DFS实现

#include<iostream>
#include "malloc.h"
using namespace std;
#define Max 100
//邻接表实现图的DFS
//邻接表每一个链表节点的结构,有一个指向下一个节点的指针,一个存放权值的结构,一个存放节点的信息
typedef struct node
{
	 int data;
	 struct node* next;
	 int info; 
}linknode;

//表头信息,每一个节点都可以成为一次表头
typedef struct nodeheader
{
	int data;
	linknode* first;
}nodeh;

typedef struct graph
{
	int n,e;
	nodeh adjaceTable[Max];
}Graph;

void initGraph(Graph* &g)
{
	cin>>g->n>>g->e;
	for(int i=0;i<g->n;i++)
	{
		cin>>g->adjaceTable[i].data;
		g->adjaceTable[i].first = NULL;
	}
	
	for(int j=1;j<=g->e;j++)
	{
		 cout<<"in"<<endl;
		 int node1,node2;
		 cin>>node1>>node2;
		 cout<<node1<<node2;
		 for(int k=0;k<g->n;k++)
	     {
	     	 cout<<"ins"<<endl;
		      if(g->adjaceTable[k].data == node1)
			 {
			     if(g->adjaceTable[k].first == NULL) 
				 {
				     linknode *nodes = (linknode*)malloc(sizeof(linknode*));
				     nodes->data = node2;
					 nodes->next = NULL;
					 g->adjaceTable[k].first = nodes;  
			     }      
				 else
			     {
			     	 linknode *p = g->adjaceTable[k].first;
				     while(p->next != NULL)
				           p= p->next;
				     linknode *nodes = (linknode*)malloc(sizeof(linknode*));
				     nodes->data = node2;
					 nodes->next = NULL;
					 p->next = nodes;
				 } 
			 }
			 
		     if(g->adjaceTable[k].data == node2)
			 {
			     if(g->adjaceTable[k].first == NULL) 
				{
				     linknode *nodes = (linknode*)malloc(sizeof(linknode*));
				     nodes->data = node1;
					 nodes->next = NULL;
					 g->adjaceTable[k].first = nodes;  
			     }      
				 else
			     {
			     	 linknode *p = g->adjaceTable[k].first;
				     while(p->next != NULL)
				           p= p->next;
				     linknode *nodes = (linknode*)malloc(sizeof(linknode*));
				     nodes->data = node1;
					 nodes->next = NULL;
					 p->next = nodes;
				 } 
			 } 
	     }
		  
		
	}
}

void printGraph(Graph* g)
{
	for(int i=0;i<g->n;i++)
	{
		cout<<g->adjaceTable[i].data;
		if(g->adjaceTable[i].first != NULL)
		{
			linknode *p = g->adjaceTable[i].first;
			cout<<p->data<<"";
			p = p->next;
			while(p != NULL)
			{
				  cout<<p->data<<"";
				  p= p->next;
			}
		}
		cout<<endl;
	}	
}

void DFS(Graph* &g,int v,int * a)
{
	a[v] = 1;
	cout<<v<<"";
	linknode *p = g->adjaceTable[v].first;
	while(p != NULL)
	{
		 if(a[p->data] == 0)
		     DFS(g,p->data,a); 
		 p = p->next;
	}
}

int main()
{
	Graph *g = (Graph*)malloc(sizeof(Graph*));
	initGraph(g);
	printGraph(g);
	int visited[g->n]; 
	for(int m=0;m<g->n;m++)
	    visited[m] = 0;
	int v = 2;
	DFS(g,v,visited);
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值