# Finding loops in a forward graph

Source: Internet
Author: User
Tags printf

Implemented by the DFS algorithm in the introduction to algorithms.

As follows:

```#include <stdio.h> enum {white, GRAY, BLACK};
struct vertex {int color;
int d, F;
int parent;

};
int time = 0;

void dfs_visit (int matrix[][6], struct vertex *v, int index);
void Dfs (int matrix[][6], struct vertex *v) {int i;
for (i = 0; i < 6; i++) {v[i].color = white;
V[I].D = 0;
V[I].F = 0;
V[i].parent =-1;
} for (i = 0; i < 6; i++) {if (V[i].color = =) {dfs_visit (Matrix, V, i);//printf ("\ n");
}}} int tmp[6];
int g_index = 0;
void dfs_visit (int matrix[][6], struct vertex *v, int index) {//printf ("%d", index);
if (V[index].color = = white) {Tmp[g_index] = index;
g_index++;
} time + = 1;
V[INDEX].D = time;

V[index].color = GRAY;
int i;
for (i = 0; i < 6, i++) {if (matrix[index][i] && v[i].color = = white) {v[i].parent = index;
Dfs_visit (Matrix, V, i);
} else if (V[i].color = = GRAY && matrix[index][i]) {int j = 0;
while (tmp[j]! = i) {j + +; } while (J < G_index) {printf ("%d-to", Tmp[j]);
j + +;
} printf ("%d\n", I);
}} time + = 1;
V[INDEX].F = time;
V[index].color =black;
g_index--;  } int main (int argc, char **argv) {int matrix[6][6] = {{1, 1, 0, 1, 1, 0}, {0, 0, 1, 0, 0, 0}, {1, 0, 0, 0, 0,

0}, {0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 0, 1}, {0, 0, 0, 1, 0, 0}};

struct vertex v[6];
DFS (Matrix, v);
return 0; }```

Output:

```0-->0
0-->1-->2-->0
3-->4-->5-->3
```

Related Keywords:

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.