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