Introduction to Algorithms 22nd: the search of graphs

Source: Internet
Author: User

The graph has two standard representations, the adjacency matrix and the adjacency table (usually the adjacency matrix is used for dense graphs, and adjacency tables are used for sparse graphs). As follows:

There are two ways to search for graphs: Depth-First search & breadth-First search.


Breadth-first searches (Breadth-first search)

Breadth-First search expands the boundaries of discovered and uncovered vertices along their breadth. That is, the algorithm first discovers all the points with the s distance of K, and then discovers the other vertices with the s distance of k+1.

Pseudo code:

EG:

Run time: O (v+e).

Depth-First traversal (Depth-first search)

In depth-first search, for the most recently discovered vertex, if he still has a change to be detected as a starting point, continue probing along this side. When all the changes to Vertex v have been explored, the search goes back to the edge where the vertex v has a starting point.

Pseudo code:

EG:


Run time: O (v+e).

=============================================================================================================== =========

Breadth First search complete code:

#include <iostream> #include <queue> #include <climits> #define UDG 0#define DG 1#define White 2#define   GRAY 3#define BLACK 4using namespace std;typedef char vtype;typedef struct gedge{vtype Adjvertex;        The adjacency vertex pointed by this edge.int weight;   The weight of this edgegedge *nextedge;         Point to the next edge}gedge;typedef struct Gvertex{vtype key;  The key of the Vertexint color;int d;vtype Pai;gedge *firstedge; Point to the first edge attached to the vertex;}   gvertex;typedef struct algraph{int vnum;int enum;int kind; The kind of Graph Gvertex *headvertex;} algraph;typedef struct edge{vtype start;vtype end;} Edge;int Locate (algraph &g,vtype s) {//locate The start vertex of one edge in head vertex of the graphfor (int i=0;i< g.vnum;i++) if (G.headvertex[i].key = = s) return i;return-1;} void Linkedgetograph (Algraph &g, Edge e) {Gedge *arc=new gedge (); Arc->adjvertex=e.end;int headv_i=locate (G, E.start); arc->nextedge=g.headverTex[headv_i].firstedge; G.headvertex[headv_i].firstedge = arc;} void Graph_create (Algraph &g, VType v[], Edge e[]) {//init The head vertexg.headvertex= new gvertex[g.vnum];for (int i=0 ; i<g.vnum;i++) {g.headvertex[i].key=v[i];  G.headvertex[i].firstedge=null;} Add edge to head vertex on order to create a graphif (G.kind = = DG)//undirected graphfor (int i=0; i<g.enum; i++) LinkE Dgetograph (G,e[i]); if (G.kind = = UDG)//directed graphfor (int i=0; i<g.enum; i++) {linkedgetograph (g,e[i]);//Link Aga In after Reversededge Temp;temp.start = E[i].end;temp.end = E[i].start; Linkedgetograph (g,temp); }}void graph_print (Algraph G) {for (int i=0; i<g.vnum; i++) {Cout<<g.headvertex[i].key;gedge *p = G.HeadVertex[i  ].firstedge;while (P! = NULL) {cout<< "--" << p->adjvertex;p = p->nextedge;  } cout<<endl; }}/*void q_print (queue<vtype> q) {cout<< "The Q is:" And while (! Q.empty ()) {Cout<<q.front () << ""; Q.pop ();} Cout<<endl;} */vtype *algraph_BFS (Algraph &g, VType s) {queue<vtype> q;vtype *bfsresult=new Vtype[g.vnum];//label the vertex:the starting Vertex becomes gray,the others become white...for (int i=0; i<g.vnum; i++) {Gvertex *hvertex=&g.headvertex[i]; Hvertex->color = White;hvertex->d = Int_max;hvertex->pai = ' 0 '; if (Hvertex->key = = s) {Hvertex->color = GRA y;hvertex->d = 0;} }//clear The Qwhile (! Q.empty ())//Making the queue Q emptyq.pop ();        Q.push (s); S enter queue q//searching layer by Layerint r_i=0;while (! Q.empty ()) {VType u,v;u= q.front ();  Q.pop ();    Delete the front element of the Qbfsresult[r_i] = u; Store the result into Array bfsresultr_i++;int h_i=locate (g,u); Gvertex *hu = &g.headvertex[h_i];gedge *p = G.headver Tex[h_i].firstedge;while (p) {v = p->adjvertex;h_i = Locate (g,v); Gvertex *HV = &g.headvertex[h_i];if (hv-> color = = White) {Hv->color = Gray;hv->d = Hv->d+1;hv->pai = u;  Q.push (v); } p = p->nextedge; } Hu->color = BLACK; }return BFsresult;} int main () {vtype v[]={' s ', ' W ', ' r ', ' V ', ' t ', ' x ', ' u ', ' y '};edge e[]={{' r ', ' V '},{' R ', ' s '},{' s ', ' W '},{' W ', ' t '},{' W ', ' x ' },{' t ', ' u '},{' t ', ' x '},{' x ', ' u '},{' x ', ' Y '},{' u ', ' Y '}; Algraph G; G.vnum=sizeof (V)/sizeof (VType); G.enum=sizeof (E)/sizeof (EDGE);           G.KIND=UDG; The kind of graphgraph_create (g,v,e);cout<< "---------------Create Graph-----------------" <<endl;cout << "The Created graph is:" <<endl; Graph_print (G);cout<< "---------------BFS Graph--------------------" <<endl;cout<< "please input The starting position: "; vtype s;cin>>s;vtype *bfsresult = new Vtype[g.vnum]; BFSRESULT=ALGRAPH_BFS (g,s);cout<< "The result of the BFS is:" <<endl;for (int i=0; i<g.vnum; i++) cout<<bfsresult[i]<< ""; Cout<<endl;return 0;}

Operation Result:


Depth first search full code:

#include <iostream> #include <iomanip>using namespace std, #define UDG 0#define DG 1#define White 0 #define GRAY 1 #define BLACK 2 #define NONE 0 #define TREE 1 #define BACK 2 #define FORWARD 3 #define CROSS 4 typedef char VT   ype;typedef struct Gedge{vtype Adjvertex;        The adjacency vertex pointed by this edge.int weight;          The weight of this edgeint type;   The type of Edgegedge *nextedge;         Point to the next edge}gedge;typedef struct Gvertex{vtype key;           The key of the Vertexint Color;int d,f;         The discovered time and the finished Timevtype Pai;  The parent node ' s key after Searchinggedge *firstedge; Point to the first edge attached to the vertex;}   gvertex;typedef struct algraph{int vnum;int enum;int kind; The kind of Graph Gvertex *headvertex;} algraph;typedef struct edge{vtype start;vtype end;} Edge;int Locate (algraph &g,vtype s) {//locate The start vertex of one edge in head vertex of the graphfor (int i=0; i<g.vnum;i++) if (G.headvertex[i].key = = s) return i;return-1;} void Linkedgetograph (Algraph &g, Edge e) {Gedge *arc=new gedge (); Arc->adjvertex=e.end;int headv_i=locate (G, E.start);arc->nextedge=g.headvertex[headv_i].firstedge; G.headvertex[headv_i].firstedge = arc;} void Graph_create (Algraph &g, VType v[], Edge e[]) {//init The head vertexg.headvertex= new gvertex[g.vnum];for (int i=0 ; i<g.vnum;i++) {g.headvertex[i].key=v[i];   G.headvertex[i].firstedge=null;} Add edge to head vertex on order to create a graphif (G.kind = = DG)//undirected graphfor (int i=0; i<g.enum; i++) LinkE Dgetograph (G,e[i]); if (G.kind = = UDG)//directed graphfor (int i=0; i<g.enum; i++) {linkedgetograph (g,e[i]);//Link Again after Reversededge Temp;temp.start = E[i].end;temp.end = E[i].start; Linkedgetograph (g,temp); }}void graph_print (Algraph G) {for (int i=0; i<g.vnum; i++) {Cout<<g.headvertex[i].key;gedge *p = G.HeadVertex[i ].firstedge;while (P! = NULL) {cout<< "--" << P-> adjvertex;p = p->nextedge;  } cout<<endl; }}void edgetype_print (Algraph G) {for (int i=0; i<g.vnum; i++) {Gedge *p = G.headvertex[i].firstedge;while (p) {cout< <G.HeadVertex[i].key<< "-" <<p->adjVertex<< ":"; switch (p->type) {case tree:cout< < "Tree Edge" <<endl;break;case back:cout<< "back Edge" <<endl;break;case forward:cout<< " Forward Edge "<<endl;break;case cross:cout<<" cross Edge "<<endl;break;} p = P->nextedge;}}} /*--------------------DFS alogithms-----------------------*/int time0;int r_i=0;void graph_dfsvisit (algraph &g,  Gvertex *u, VType *r) {TIME0 = TIME0 +1; White vertex u have just been discoveredu->d = TIME0; u->color = Gray;gedge *p = U->firstedge;while (p) {VType V = P->adjvertex;int h_i=locate (g,v); Gvertex *HV = &g.headvertex[h_i];//classify The Edge and recursive searchingif (Hv->color = = white) {Hv->pai = u->key;      Graph_dfsvisit (g,hv,r);p->type = TREE;  Tree Edge}else if (hv->color = = GRAY) {p->type = back; Back Edge}else if (Hv->color = = BLACK) {if (U->d < hv->d) P->type = FORWARD;//forward edgeelsep->type = C  ROSS; Cross edge}p = P->nextedge;}  U->color = BLACK;   Backen U;it is finishedr[r_i++]=u->key; Store the DFS result into array RTIME0 = TIME0 +1;u->f = TIME0;} void Algraph_dfs (Algraph &g, VType *result) {//init all the Vertexgvertex *u;for (int i=0; i<g.vnum; i++) {u = &G. Headvertex[i];u->color = White;u->pai = ' 0 ';}  TIME0 = 0; Time Stamp//explore every vertexfor (int i=0; i<g.vnum; i++) {u = &g.headvertex[i];if (U->color = = white) Graph_ Dfsvisit (G,u,result);} }/*----------------------------------------------*/int Main () {VType v[]={' u ', ' x ', ' V ', ' y ', ' w ', ' z '};edge e[]={{' u ', ' X '},{' u ', ' V '},{' x ', ' V '},{' V ', ' y '},{' y ', ' x '},{' W ', ' Y '},{' w ', ' z '},{' z ', ' Z '}; Algraph G; G.vnum=sizeof (V)/sizeof (VType); G.enum=sizeof (E)/sizeof (EDGE);           G.KIND=DG; The kind of grapHgraph_create (g,v,e);cout<< "---------------Create Graph-----------------<<endl;cout<<" the Created graph is: "<<endl; Graph_print (G);cout<< "---------------DFS Graph--------------------" <<endl;vtype *dfsresult = new vtype[ G.vnum]; Algraph_dfs (G,dfsresult);cout<< "The result of DFS is:" <<endl;for (int i=0; i<g.vnum; i++) cout<<dfsresult[i]<< "";cout<<endl;cout<< "the discovered time and finished time Respectivly is: "<<endl;for (int i=0; i<g.vnum; i++) COUT&LT;&LT;G.HEADVERTEX[I].KEY&LT;&LT;SETW (4) &LT;&LT;G.HEADVERTEX[I].D&LT;&LT;SETW (4) <<G.HeadVertex [i].f<<endl;cout<< "The Edge type information is:" <<endl; Edgetype_print (G);cout<< "--------------------------------------------" <<endl;return 0;}

Operation Result:


"Note: If there is an error, please correct me ~ ~ ~"

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Introduction to Algorithms 22nd: the search of graphs

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.