图的邻接表的生成、深搜、广搜

#include<iostream>
using namespace std;


struct node
{
int num;
int val;
struct node *next;
};

struct gpnode
{
int data;
struct node *link;
};

//由键盘输入生成图邻接表
struct gpnode *create_Link_GP(int n) //n是图中节点个数
{
int seq, v;
struct node *p;
struct gpnode *gp = (struct gpnode *)malloc(n * sizeof(struct gpnode)); //申请邻接表中顺序存储空间
for(int k = 0; k < n; k ++){ //依次对图中的每一个节点建立链接所有后件的单链表
(gp + k)->data = k;
(gp + k)->link = NULL;
cout << "输入途中第" << k + 1 << "个节点的后件信息:" << endl;

while(1){
scanf("%d %d", &seq, &v);
if(seq == -1 && v == -1){
break;
}
p = (struct node *)malloc(sizeof(struct node)); //申请单链表节点
p->num = seq;
p->val = v;
p->next = (gp + k)->link; //新节点指针指向原节点,即成为被链接的第一个节点
(gp + k)->link = p;
}
}
return gp;
}

//输出图邻接表
void print_Link_GP(struct gpnode *gp, int n)
{
struct node *p;
for(int k = 0; k < n; k ++){
cout << (gp + k)->data;
p = (gp + k)->link;
while(p){
cout << "--->";
cout << p->num << ' ' << p->val;
p = p->next;
}
cout << endl;
}
return ;
}


//深搜
void dfs(struct gpnode *q, int k, bool visit[])
{
struct node *p;
cout << (q + k)->data << ' ';
visit[k] = true;
p = (q + k)->link;
while(p){
if(!visit[p->num]){
dfs(q, p->num, visit);
}
p = p->next;
}
return ;
}

void dfs_Link_GP(struct gpnode *q, int n)
{
bool *visit = (bool *)malloc(n * sizeof(bool)); //标志该节点是否已出现
for(int k = 0; k < n; k ++){
visit[k] = false;
}
//memset(visit, false, sizeof(visit)); 结果是visit[4]和visit[6]是true
/*for(int i = 0; i < n; i ++){
if(visit[i]){
cout << "visit[" << i << "]:true" << endl;
}
else{
cout << "visit[" << i << "]:false" << endl;
}
}
*/
for(int k = 0; k < n; k ++){
if(!visit[k]){
dfs(q, k, visit); //对每个图节点深搜
}
}
cout << endl;
free(visit);
return ;
}

//广搜
void bfs_Link_GP(struct gpnode *gp, int n)
{
bool visit[n];
memset(visit, false, sizeof(visit));

int qlist[n];
qlist[0] = gp->data;
visit[gp->data] = true;
int head = 0;
int tail = 1;

struct node *p;
while(head < tail){ //队列不空
int x = qlist[head];
cout << x << ' ';
p = (gp + x)->link;
while(p){
int tmp = p->num;
if(!visit[tmp]){
qlist[tail ++] = tmp;
visit[tmp] = true;
}
p = p->next;
}
head ++;
}
return ;
}

int main()
{
int n = 8;
struct gpnode *gp = create_Link_GP(n);
print_Link_GP(gp, n);

   cout << "深搜" << endl;
   dfs_Link_GP(gp, n);
   cout << "广搜" << endl;
   bfs_Link_GP(gp, n);
   cout << endl;

    system("pause");

}

你可能感兴趣的:(生成)