Look at the data structure write code (44) Determine if there is a loop on the graph

Source: Internet
Author: User

Tag: Determine if there is a loop-free graph for the non-circular graph.

When looking at the data structure of Min 7.5, the book says, "It is not without the complexity to judge whether there is a ring to the graph." For a non-directed graph, a loop is bound to occur when a back edge is encountered during a depth-first traversal (that is, an edge that points to a vertex that has been visited) . See not understand, so online Baidu a bit.

With the idea: so write down algorithms and ideas, so that later temperature.

Ideas:

1. An n vertex, an e>= diagram of the e-bar, if n, there must be a loop .

2. If e < n requires a deep traversal and passes the parent node into the parameter, there is a loop if it encounters a node that has been accessed and is not a parent node .

On the code:

void Dfscycle (Graph g,int curent,int parent,bool * Isvisited,bool * is) {isvisited[curent] = true; Arcnode * next = G.list[curent].head->nextarc;for (; next! = NULL; next = next->nextarc) {int index = Next->adjvex ; if (isvisited[index] = = False) {dfscycle (g,index,curent,isvisited,is);} else if (index! = parent) {*is = true;}}} BOOL Iscycle (Graph g) {if (G.arcnum >= g.vexnum) {return true;} BOOL Isvisited[max_vertex_num] = {False};bool is = false;for (int i = 0; i < G.vexnum; i++) {if (isvisited[i] = = False) { Dfscycle (G,i,-1,isvisited,&is); if (IS) {//existence loop, Exit function return True;}}} return is;} int _tmain (int argc, _tchar* argv[]) {Graph g;graphcreate (&g);p rintgrahp (g); char * is = iscycle (g)? "Have loop": "No Loop";p rintf ("Figure%s\n", is);//The timely destruction of memory is a good habit graphdestory (&g); return 0;}
Run:

Full Code Web address: Click to open link




Look at the data structure write code (44) Determine if there is a loop on the graph

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.