图的广度优先搜索BFS(C++)

来源:互联网 发布:js小数做加减 编辑:程序博客网 时间:2024/05/22 10:59

用于实验的图:

r->2; 1->s; t->3; u->4; v->5; w->6; x->7; y->8


这里对链表的结构进行了改编:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */ #include <iostream> #include <queue> #include <stack> #include <vector> #include <climits> using namespace std; struct ListNode{ int val; int color;//white=0,gray=1,black=2;白表示未搜索,灰表示边界,灰点的邻接节点有些遍历了有些没有;黑色表示节点周围都遍历了 int d; vector<ListNode*> next;//存储所有的邻接节点  ListNode* pre;//便于回寻,它是从哪来的 ListNode(int x):color(0),val(x),d(16),pre(NULL){ } }; void insert(ListNode* L,ListNode* n){L->next.push_back(n);}void show(ListNode* L){int n=L->next.size();for(int i=0;i<n;i++)cout<<(L->next)[i]->val<<" ";}void BFS(ListNode* & s){s->color=1;s->d=0;queue<ListNode*> q;q.push(s);while(!q.empty()){ListNode* u=q.front();q.pop();int n=u->next.size();for(int i=0;i<n;i++){        ListNode* v=(u->next)[i];if(v->color==0){v->color=1;v->d=u->d+1;v->pre=u;q.push(v);}}u->color=2;}return;} void find_path(ListNode* t)//找到从起点s到终点t的其中一条最短路径{stack<ListNode*> path;   path.push(t);   ListNode* y=t->pre;   while(y)    {   path.push(y);   y=y->pre;   }   while(path.size()>0)   {   ListNode* t=path.top();   cout<<t->val<<" ";   path.pop();   }} int main(){
   <span style="font-family: Arial, Helvetica, sans-serif;">ListNode* a[8];</span>
   int b[8][8]={{2,6},{1,5},{4,6,7},{3,8},{1},{1,3,7},{3,4,6,8},{4,7}};   for(int i=0;i<8;i++)   {   a[i]=new ListNode(i+1);   }   for(int j=0;j<8;j++)   {   for(int i=0;i<8;i++)   if(b[j][i])   a[j]->next.push_back(a[b[j][i]-1]);   }   BFS(a[0]);//以a[0]为起点,搜索整个图    for(int i=0;i<8;i++)   cout<<a[i]->d<<" ";   cout<<endl;//显示从1节点到其他节点的距离    //从节点1(a[0])到节点8(a[7])的线路   find_path(a[7]);}


0 0
原创粉丝点击