图的创建,深度,广度优先遍历

#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
#define MAX 5
static bool visited[MAX]={false,false,false,false,false};
typedef struct node
{
	int node_data;
	struct node * next;
}*Node;
 typedef struct
{
	int data;
	struct node * head;
}Mapnode,Map[MAX];
void create_nodenext(struct node * head)
{
	vector<int> all_node_num;
	int node_num;
	Node p;
	Node q;
	q=head;
	for(int i=0;i<MAX;)
	{
		cout<<"输入连接的节点编号(输入负数表示输入完毕):";
		cin>>node_num;
		if(node_num==-1)
		{
			break ;
		} 
		else
		{
			bool flag=false;
			for(int j=0;j<all_node_num.size();j++)
			{
				if(all_node_num[j]==node_num)
				{
					flag=true;
					break;
				}
			}
			if(flag||node_num>=MAX)
			{
				cout<<"输入重复!请重新输入!"<<endl;
			}
			else
			{
				head->node_data++;
				p = new struct node;
				p->node_data=node_num;
				all_node_num.push_back(node_num);
				q->next=p;
				q=q->next;
				i++;
			}
		}
	}
	q->next=NULL;
	q=q->next;
}
void delete_nodenext(Node head)
{
	Node p = head;
	while(p!=NULL)
	{
		p=p->next;
		delete head;
		head=p;
	}
	delete head;
}
void delete_map(Map map)
{
	for(int i=0;i<MAX;i++)
	{
		delete_nodenext(map[i].head);
	}
}
void createMap(Map map)
{
	for(int i=0;i<MAX;i++)
	{
		cout<<"输入第"<<i<<"个节点的值"<<endl;
		cin>>map[i].data;
		map[i].head = new struct node;
		map[i].head->node_data=0;
		
		create_nodenext(map[i].head);
	}
}
void DFS(Map map,int node_num)
{
	cout<<map[node_num].data<<endl;
	visited[node_num]=true;
	struct node * p = map[node_num].head;
	if(p==NULL||p->next==NULL)
	{
		//cout<<"P为NULL"<<endl;
		return ;
	}
	while(p->next!=NULL)
	{
		p=p->next;
		//cout<<"循环中"<<endl; 
		//system("pause");
		//printf("\n跳转到%d\n",p->node_data);
		if(!(visited[p->node_data]))
		{
			//printf("可以访问!\n");
			//cout<<map[p->node_data].data;
			DFS(map,p->node_data);
		}
		
	}
}
void DFSMap(Map map)
{
	cout<<"深度优先算法:"<<endl; 
	for(int i=0;i<MAX;i++)
	{
		visited[i]=false;
	}
	for(int i=0;i<MAX;i++)
	{
		if(!visited[i])
		{
			//cout<<"第i个送入检验!"<<endl;
			DFS(map,i);
		}
	}
}
void BFSMap(Map map)
{
	cout<<"广度优先算法:"<<endl; 
	for(int i=0;i<MAX;i++)
	{
		visited[i]=false;
	}
	vector<int> node_num;
	for(int i=0;i<MAX;i++)
	{
		node_num.push_back(i);
		Node p = map[i].head;
		if(p==NULL)
		{
			continue;
		}
		while(p->next!=NULL)
		{
			p=p->next;
			node_num.push_back(p->node_data);
		}
	}
	for(int i=0;i<node_num.size();i++)
	{
		if(!visited[node_num[i]])
		{
			cout<<map[node_num[i]].data<<endl;
			visited[node_num[i]]=true;
		}
	}
}
int main()
{
	Map map;
	createMap(map);
	DFSMap(map);
	BFSMap(map);
	delete_map(map);
	system("pause");
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值