-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathConnected_Dfs.cpp.bak
130 lines (100 loc) · 2.34 KB
/
Connected_Dfs.cpp.bak
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <iostream>
#include <cstdlib>
#define MAX 1000
int time = 0;
int smallest_component = 100000;
int count = 0;
enum
{
white, gray, black
}color;
struct Node
{
int dest;
int color;
Node* next;
};
struct Adj
{
Node *list;
};
int D[MAX];
int F[MAX];
int Color[MAX];
void printGraph(Adj *list, int vertices);
void DFS(Adj* list, int vertex);
void addEdge(Adj* list, int v, int dest)
{
Node* temp = new Node;
temp->next = list[v].list;
temp->dest = dest;
list[v].list = temp;
Node* temp2 = new Node;
temp2->next = list[dest].list;
temp2->dest = v;
list[dest].list = temp2;
}
int main()
{
int vertex1 = 0, vertex2 = 0;
int vertex_count=0;
Node *head = NULL;
int v = 1;
int u = 1;
int connected_components = 0;
fscanf(in, "%d", &vertex_count);
int vertices = vertex_count + 1;
//Create the struct pointer and call the function to create the Graph
Adj* list = (Adj*)malloc(sizeof(Adj)*vertices);
for(v=1; v<vertices; v++){
Color[v] = white;
}
//run through each pair of numbers
while(fscanf(in, "%d %d", &vertex1, &vertex2)!=EOF)
{
// create the first list
addEdge(list, vertex1, vertex2);
}
printf("\n\n");
Node *temp;
//run through the graph's nodes
for (v = 1; v < vertices; v++)
{
count = 0;
if(Color[v] == white){
DFS(list, v);
connected_components++;
if(smallest_component>count)
smallest_component=count;
}
}
printf("The number of connected components is %d\n", connected_components);
printf("The smallest component has %d vertices\n", smallest_component);
free(list);
//printGraph(myGraph);
return 0;
}
//Run a DFS given the Adjacency list and vertex in the list
void DFS(Adj* list, int vertex)
{
count++;
//printf("\nI am in DFS with node %d \n", vertex);
Color[vertex] = gray;
time = time + 1;
D[vertex] = time;
Node *temp;
for(temp = list[vertex].list; temp != NULL; temp = temp->next)
{
if(Color[temp->dest] == white)
DFS(list, temp->dest);
}
//get the new time, color, and end time
time = time+1;
F[vertex] = time;
//this means that we backtracked and now the node is black
Color[vertex] = black;
}
/*
* This function creates the edge between the two vertices.
* Since we have an UNDIRECTED graph, when I create the edges, I create them for both vertex and destination
*/