Graph algorithm (a)--basic graph algorithm (BFS,DFS and its application) (1)

Source: Internet
Author: User

1) BFS

Breadth-First search: Given source node s, generate breadth-first search tree
The simple path from node s to node V in the breadth-first search tree corresponds to the shortest path from S to V (the path with the least number of edges)
Breadth first: The boundary between the discovered node and the uncovered node (the gray node) expands outwards along its breadth

1#include <stack>2#include <vector>3#include <queue>4#include <algorithm>5 6 using namespacestd;7 #defineINF 999999998 #defineNIL-19 intN;Ten intg[ +][ +]; One structNode A { -     intcolor; -     intD//Distance the     intPi//Pi,ancestor -}t[ +]; -queue<int>Q; -  + voidBFS (ints) - { +      for(intI=0; i<n;i++) A     { at         if(i!=s) -         { -T[i].color =0; -T[I].D =INF; -T[i].pi =NIL; -         } in     } -T[s].color =1; toT[S].D =0; +T[s].pi =NIL; - Q.push (s); the      while(!q.empty ()) *     { $         intU =Q.front ();Panax Notoginseng Q.pop (); -          for(intv=0; v<n;v++) the         { +             if((g[u][v] = =1) && (U! =v)) A             {     the                 if(T[v].color = =0) +                 { -T[v].color =1; $T[V].D = T[u].d +1; $T[v].pi =u; - Q.push (v); -                 } the             } -         }WuyiT[u].color =1; the     } - } Wu  - /* About int main () $ { - While (cin>>n) -     { - for (int i=0;i<n;i++) A         { + for (int j=0;j<n;j++) the             { - cin>>g[i][j]; $             } the         } the int s; the cin>>s; the BFS (s); - for (int i=0;i<n;i++) in         { the cout<<i<< "" <<t[i].d<< "" <<t[i].pi<<endl; the         } About     } the return 0; the } the */

  

Graph algorithm (a)--basic graph algorithm (BFS,DFS and its application) (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.