邻接表存储图利用BFS遍历
生活随笔
收集整理的這篇文章主要介紹了
邻接表存储图利用BFS遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//今天上機寫的鄰接表存儲圖利用BFS遍歷:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
struct node//存節點所連接的點
{int id;node *next;
};
struct list//存各個節點的頂點值
{int data;node *first;
}AdjList[1000];
struct ALGraph
{int v,n;//v頂點數,邊數
}ALGraph;
int vis[1000];//訪問標記
void create_list(node *&head,int n)
{node *p=head;for(int i=0;i<n;++i){node *pnew=new node;scanf("%d",&pnew->id);pnew->next=NULL;p->next=pnew;p=p->next;}p->next=NULL;p=head->next;while(p){printf("%d ",p->id);p=p->next;}putchar('\n');
}
void createAdjList()
{printf("請輸入領接表的頂點和弧數:");scanf("%d%d",&ALGraph.v,&ALGraph.n);for(int i=1;i<=ALGraph.v;++i){printf("請輸入第%d個頂點值\n",i);scanf("%d",&AdjList[i].data);printf("請輸入該點所相鄰點的個數:");int n;scanf("%d",&n);printf("如果相鄰點存在請輸入各個頂點,不存在請輸入下個頂點信息\n");node *head=new node;if(n>0){create_list(head,n);AdjList[i].first=head->next;//第一個為空}elseAdjList[i].first=NULL;}
}
void BFS()
{printf("%d ",AdjList[1].data);for(int i=1;i<=ALGraph.v;++i){while(AdjList[i].first&&!vis[i]){printf("%d ",AdjList[i].first->id);AdjList[i].first=AdjList[i].first->next;vis[i]=1;}}/*for(int i=1;i<=ALGraph.v;++i){cout<<AdjList[i].data<<" ";while(AdjList[i].first){printf("%d ",AdjList[i].first->id);AdjList[i].first=AdjList[i].first->next;}putchar('\n');}*/putchar('\n');
}
int main()
{memset(vis,0,sizeof(vis));int x;createAdjList();BFS();return 0;
}
總結
以上是生活随笔為你收集整理的邻接表存储图利用BFS遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IT技术网站
- 下一篇: 图结构练习——最短路径