#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;
}
图的创建,深度,广度优先遍历
最新推荐文章于 2022-09-01 22:48:27 发布