REf
http://simplestcodings.blogspot.in/2013/09/graphs.html
http://simplestcodings.blogspot.in/2013/09/graphs.html
http://sun.iwu.edu/~sander/CS255/Notes/AdjLists.html
http://www.sanfoundry.com/cpp-program-describes-graph-representation-using-adjacency-list/
http://iamsoftwareengineer.blogspot.in/2012/06/c-graph-implementation-with-adjacency.html
http://stackoverflow.com/questions/11547875/graph-adjacency-list-representation
http://www.geeksforgeeks.org/graph-and-its-representations/
#include <stdio.h>
#include <stdlib.h>
struct graphnode
{
int name;
struct graphnode *next;
};
void addNode(struct graphnode *G[],int startNode, int endNode)
{
// creating a new linked list which is to be added
struct graphnode *tmp;
tmp->name=endNode;
tmp->next=G[startNode];
startNode=tmp;
}
void printGraph(struct graphnode *G[], int numofnodes)
{
int i;
for(i=0;i<numofnodes;i++)
{
struct graphnode *tmp;
tmp=G[i];
printf("%d",i);
while(tmp!=NULL)
{
printf("%d",tmp->name);
tmp=tmp->next;
}
}
}
int main(void)
{
int numofnodes;
printf("Enter the number of nodes: ");
scanf("%d",&numofnodes);
// Note that we have created depending upon the size inputted by the user
struct graphnode *arrayOfVertices[numofnodes];
int i; // for iteration
for(i=0;i<numofnodes;i++)
{
arrayOfVertices[i]->name=i;
arrayOfVertices[i]->next=NULL;
}
addNode(arrayOfVertices,0,1);
addNode(aarrayOfVertices,0,2);
printGraph(arrayOfVertices,numofnodes);
return 0;
}
C Graph implementation with adjacency list representation using structures: Data Structure Tutorial 1
looking on the web to have a simple introductory tutorial on graphs, but unfortunately couldn’t find one
simple enough. So I decided to write this.
Let us first define the structure of a vertex in a graph.
The vertexKey is the data field of the vertex, and edgePtr is the edge pointer, declared next.
The graph can be declared as:
Here, we are taking the maximum number of vertices as 10.
The vertexCount gives us the number of vertices in the graph at a time.
{
array is connected.
The following figure should make the structures clear:
We have to insert a new vertex without any edges.
This can be implemented by incrementing the vertexCount and storing the vertex data in the
graph array at vertexCount position.
Note that the edgePtr of the newly inserted vertex should point to NULL, i.e., it is a null
pointer.
For inserting an edge, we just move to the end of the linked list of the corresponding vertex,
and insert new edge there. We have to do this for both the vertices.
To summarize, the full code is given below:
And the final output is:
‘delete vertex’ operation. For this, we will have to use a linked list instead of an array for
storing the vertices. This is shown below:
That completes our first tutorial on graphs. In the next tutorial, we will discuss graph
operations like ‘depth-first-search’, ‘breadh-first-search’ etc.
If you like this post, please consider to buy me a coffee.
View comments
Love might not prevail, but chances are, at least one of the domains in 1,930 applications for new extensions will.
The Government of Byteland has decide to issue new currency notes with special protection features to commemorate a great mathematician.
OrganizerCompareall(Start-up)
Important Dates
Start Date: June 10, 2012
End Date : June 5, 2012
Deadline: June 30, 2012
Eligibility Undergrad Level
Type of Opportunity Internship/Training
Published OnJune 5, 2012
Need a website developer for start up by IITian.
OrganizeriLogo(Start-up)
Important Dates
Start Date: June 1, 2012
Deadline: June 11, 2012
Eligibility Undergrad Level,Grad Level,Postgrad Level,Non-students
Type of Opportunity Internship/Training
Tags Technology, Software Engg./Coding/Programming
Published OnMay 30, 2012
Abou
These edges may be directed or undirected. Moreover these edges can have weights associated with them
So edges can be categorized as :
- Directed, weighted edges
- Directed, unweighted edges
- Undirected, weighted edges
- Undirected, unweighted edges
Uses of graphs
Graphs are extremely useful. Look everywhere and one can easily find use of graphs. Listed below are a few of the vast set of practical uses of graphs.Delhi Metro Rail Map |
A Maze |
A tournament fixture Courtesy: http://www.squadtd.com/ |
Kind of graphs
- Undirected Graphs
Undirected Graph |
- Order of vertices doesn't matter
- 1-2 is same as 2-1
- Directed Graphs
Directed Graph |
- Order of vertices does matter
- 1-2 is not same as 2-1
- Vertex labeled Graphs.
Vertex Labeled Graph |
- Each vertex contains additional information. e.g {2,orange}, {4,green}
- Cyclic Graphs.
Cyclic Graph |
- Graph contains at least one cycle.
- Edge labeled Graphs.
Edge Labeled Graph |
- Edge has labels e.g an edge in the above graph will be represented as {orange,green,{blue,cyan}}
- Weighted Graphs.
Weighted Graph |
- Each edge has some weight associated with it.
- Directed Acyclic Graphs.
Direct Acyclic Graph(DAG) |
- Graph has no cycles.
- Disconnected Graphs
Disconnected Graph |
- Vertices are disconnected
- Mixed graph
Mixed Graph |
- Some edges may be directed and some may be undirected
- Multigraph
Multigraph |
- Multiple edges (and sometimes loops) are allowed
- Quiver
- Directed graph which may have more than one arrow from a given source to a given target. A quiver may also have directed loops in it.
Representation of graphs:
Fig. 1: An undirected graph |
Fig 2: A directed graph |
Adjacency Matrix :
A[i][j] = 1 if there is an edge E(i,j)
= 0 otherwise
For an undirected graph, A[i][j] = A[j][i]
For weighted graphs,
A[i][j] = weight of the edge, if there is an edge E(i,j)
= a constant representing no edge (e.g a very large or very small value)
For Fig 1, the adjacency matrix would be
Adjacency List :
Every vertex has a linked list of the vertices it is connected with.
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
| /*graph.h*/ #ifndef _GRAPH_H_ #define _GRAPH_H_ typedef enum {UNDIRECTED=0,DIRECTED} graph_type_e; /* Adjacency list node*/ typedef struct adjlist_node { int vertex; /*Index to adjacency list array*/ struct adjlist_node *next; /*Pointer to the next node*/ }adjlist_node_t, *adjlist_node_p; /* Adjacency list */ typedef struct adjlist { int num_members; /*number of members in the list (for future use)*/ adjlist_node_t *head; /*head of the adjacency linked list*/ }adjlist_t, *adjlist_p; /* Graph structure. A graph is an array of adjacency lists. Size of array will be number of vertices in graph*/ typedef struct graph { graph_type_e type; /*Directed or undirected graph */ int num_vertices; /*Number of vertices*/ adjlist_p adjListArr; /*Adjacency lists' array*/ }graph_t, *graph_p; /* Exit function to handle fatal errors*/ inline void err_exit( char * msg) { printf ( "[Fatal Error]: %s \nExiting...\n" , msg); exit (1); } #endif |
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
131
132
133
134
135
| /*graph.c*/ #include <stdio.h> #include <stdlib.h> #include "graph.h" /* Function to create an adjacency list node*/ adjlist_node_p createNode( int v) { adjlist_node_p newNode = (adjlist_node_p) malloc ( sizeof (adjlist_node_t)); if (!newNode) err_exit( "Unable to allocate memory for new node" ); newNode->vertex = v; newNode->next = NULL; return newNode; } /* Function to create a graph with n vertices; Creates both directed and undirected graphs*/ graph_p createGraph( int n, graph_type_e type) { int i; graph_p graph = (graph_p) malloc ( sizeof (graph_t)); if (!graph) err_exit( "Unable to allocate memory for graph" ); graph->num_vertices = n; graph->type = type; /* Create an array of adjacency lists*/ graph->adjListArr = (adjlist_p) malloc (n * sizeof (adjlist_t)); if (!graph->adjListArr) err_exit( "Unable to allocate memory for adjacency list array" ); for (i = 0; i < n; i++) { graph->adjListArr[i].head = NULL; graph->adjListArr[i].num_members = 0; } return graph; } /*Destroys the graph*/ void destroyGraph(graph_p graph) { if (graph) { if (graph->adjListArr) { int v; /*Free up the nodes*/ for (v = 0; v < graph->num_vertices; v++) { adjlist_node_p adjListPtr = graph->adjListArr[v].head; while (adjListPtr) { adjlist_node_p tmp = adjListPtr; adjListPtr = adjListPtr->next; free (tmp); } } /*Free the adjacency list array*/ free (graph->adjListArr); } /*Free the graph*/ free (graph); } } /* Adds an edge to a graph*/ void addEdge(graph_t *graph, int src, int dest) { /* Add an edge from src to dst in the adjacency list*/ adjlist_node_p newNode = createNode(dest); newNode->next = graph->adjListArr[src].head; graph->adjListArr[src].head = newNode; graph->adjListArr[src].num_members++; if (graph->type == UNDIRECTED) { /* Add an edge from dest to src also*/ newNode = createNode(src); newNode->next = graph->adjListArr[dest].head; graph->adjListArr[dest].head = newNode; graph->adjListArr[dest].num_members++; } } /* Function to print the adjacency list of graph*/ void displayGraph(graph_p graph) { int i; for (i = 0; i < graph->num_vertices; i++) { adjlist_node_p adjListPtr = graph->adjListArr[i].head; printf ( "\n%d: " , i); while (adjListPtr) { printf ( "%d->" , adjListPtr->vertex); adjListPtr = adjListPtr->next; } printf ( "NULL\n" ); } } int main() { graph_p undir_graph = createGraph(5, UNDIRECTED); graph_p dir_graph = createGraph(5, DIRECTED); addEdge(undir_graph, 0, 1); addEdge(undir_graph, 0, 4); addEdge(undir_graph, 1, 2); addEdge(undir_graph, 1, 3); addEdge(undir_graph, 1, 4); addEdge(undir_graph, 2, 3); addEdge(undir_graph, 3, 4); addEdge(dir_graph, 0, 1); addEdge(dir_graph, 0, 4); addEdge(dir_graph, 1, 2); addEdge(dir_graph, 1, 3); addEdge(dir_graph, 1, 4); addEdge(dir_graph, 2, 3); addEdge(dir_graph, 3, 4); printf ( "\nUNDIRECTED GRAPH" ); displayGraph(undir_graph); destroyGraph(undir_graph); printf ( "\nDIRECTED GRAPH" ); displayGraph(dir_graph); destroyGraph(dir_graph); return 0; } |
Sources:
http://en.wikipedia.org/wiki/Graph_(mathematics)
http://web.cecs.pdx.edu/~sheard/course/Cs163/Doc/Graphs.html
http://msdn.microsoft.com/en-us/library/ms379574(v=vs.80).aspx
Builder Design Pattern |
- Director: It constructs an object using the Builder interface.
- Builder : It specifies an abstract interface to build parts of a product.
- Concrete Classes : Implements builder interface.
- Product : The complex object which is created at the end.
- When the object to be created is complex enough and can have multiple representations.
- When the construction process can be broken down into multiple steps
- When the process of creation of an object can be independent of the parts to be used.
- When different products can have a common abstract class.
Builder Example |
In this example we create house as product. Now the house created may be different as per requirement of different people. It can be a lavish house with lots of amenities and expensive stuff. On the other hand, it could be a normal house with normal stuff.
- The HouseBuilder class is the builder class which provides interface for creating the parts of the house.
- The House class is the final product that we want to build
- LavishHouse and NormalHouse are the concrete classes which implement the HouseBuilder interface.
- Contractor is the director which constructs the house using the HouseBuilder interface.
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
| #include <iostream> using namespace std; /* Interface that will be returned as the product from builder */ class HousePlan{ public : virtual void setWindow(string window)=0; virtual void setDoor(string door)=0; virtual void setBathroom(string bathroom)=0; virtual void setKitchen(string kitchen)=0; virtual void setFloor(string floor )=0; }; /* Concrete class for the HousePlan interface */ class House: public HousePlan{ private : string window, door, kitchen, bathroom, floor ; public : void setWindow(string window) { this ->window = window; } void setDoor(string door) { this ->door = door; } void setBathroom(string bathroom) { this ->bathroom = bathroom; } void setKitchen(string kitchen) { this ->kitchen = kitchen; } void setFloor(string floor ) { this -> floor = floor ; } }; /* Builder Class */ class HouseBuilder { public : /* Abstract functions to build parts */ virtual void buildWindow()=0; virtual void buildDoor()=0; virtual void buildKitchen()=0; virtual void buildBathroom()=0; virtual void buildFloor()=0; /* The product is returned by this function */ virtual House* getHouse()=0; }; /* Concrete class for the builder interface */ class LavishHouse: public HouseBuilder{ private : House *house; public : LavishHouse() { house = new House(); } void buildWindow() { house->setWindow( "French Window" ); } void buildDoor() { house->setDoor( "Wooden Door" ); } void buildBathroom() { house->setBathroom( "Modern Bathroom" ); } void buildKitchen() { house->setKitchen( "Modular Kitchen" ); } void buildFloor() { house->setFloor( "Wooden Floor" ); } House* getHouse() { return this ->house; } }; /* Another Concrete class for the builder interface */ class NormalHouse: public HouseBuilder{ private : House *house; public : NormalHouse() { house = new House(); } void buildWindow() { house->setWindow( "Normal Window" ); } void buildDoor() { house->setDoor( "Metal Door" ); } void buildBathroom() { house->setBathroom( "Regular Bathroom" ); } void buildKitchen() { house->setKitchen( "Regular Kitchen" ); } void buildFloor() { house->setFloor( "Mosaic Floor" ); } House* getHouse() { return this ->house; } }; /* The Director. Constructs the house */ class Contractor { private : HouseBuilder *houseBuilder; public : Contractor(HouseBuilder *houseBuilder) { this ->houseBuilder = houseBuilder; } House *getHouse() { return houseBuilder->getHouse(); } void buildHouse() { houseBuilder->buildWindow(); houseBuilder->buildDoor(); houseBuilder->buildBathroom(); houseBuilder->buildKitchen(); houseBuilder->buildFloor(); } }; /* Example on how to use the Builder design pattern */ int main() { HouseBuilder *lavishHouseBldr = new LavishHouse(); HouseBuilder *normalHouseBldr = new NormalHouse(); Contractor *ctr1 = new Contractor(lavishHouseBldr); Contractor *ctr2 = new Contractor(normalHouseBldr); ctr1->buildHouse(); House *house1 = ctr1->getHouse(); cout<< "Constructed: " <<house1; ctr2->buildHouse(); House *house2 = ctr2->getHouse(); cout<< "Constructed: " <<house2; } |
C program for dfs (depth first search)
C program for dfs
#include<stdio.h> #include<conio.h> char stack[20]; int top=-1, n; char arr[20]; char dfs(int ); char ajMat[20][20]; char b[20]; void display(); int p=0; int main() { char v; int l=0; printf("Enter the number of nodes in a graph"); scanf("%d",&n); printf("Enter the value of node of graph"); for(int i=0; i<n; i++) { scanf("%s",&b[i]); } char k=b[0]; printf("Enter the value in adjancency matrix in from of 'Y' or 'N'\n"); printf("\nIf there is an edge between the two vertices then enter 'Y' or 'N'\n"); for(int i=0; i<n; i++) printf(" %c ",b[i]); for(int i=0;i<n; i++) { printf("\n%c ",b[i]); for(int j=0; j<n; j++) { printf("%c ",v=getch()); ajMat[i][j]=v; } printf("\n\n"); } for(int i=0;i<n;i++) { l=0; while(k!=b[l]) l++; k=dfs(l); } display(); getch(); } void display() { printf(" DFS of Graph : "); for(int i=0; i<n; i++) printf("%c ",arr[i]); } void push(char val) { top=top+1; stack[top]=val; } char pop() { return stack[top]; } bool unVisit(char val) { for(int i=0; i<p; i++) if(val==arr[i]) return false; for(int i=0; i<=top; i++) if(val==stack[top]) return false; return true; } char dfs(int i) { int k; char m; if(top==-1) { push(b[i]); } m=pop(); top--; arr[p]=m; p++; for(int j=0; j<n; j++) { if(ajMat[i][j]=='y') { if(unVisit(b[j])) { push(b[j]); } } } return stack[top]; }Here is the Graph for below output :
Output of C program for dfs:
One thought on “C program for dfs (depth first search)”
-
i need to find tree edges and back edges program.would you help me..?
Leave a Reply
Code Coding
https://www.google.co.in/search?biw=1138&bih=526&q=breadth+first+search+program+in+c&revid=1534365621&sa=X&ei=pS8fVMOvNIvluQSfg4LoBQ&sqi=2&ved=0CH8Q1QIoBA
https://www.google.co.in/search?biw=1138&bih=526&q=dfs+program+in+c+with+output&revid=1534365621&sa=X&ei=pS8fVMOvNIvluQSfg4LoBQ&sqi=2&ved=0CIEBENUCKAY
Where I can find it?
Here in the main() function, I have hard-coded the edges and vertices, which can be scanned using scanf(). Also, if you intend to read input from a file, you can put the scan statements in the main function, compile the program to exe, say out.exe (considering you are using windows), and in the command prompt, type "out.exe <input.txt" (without quotes), where input.txt contains the required input.
first collumn of file represent vertex of graph
n all the elements of row(except 1st )represents the edges of vertex (1st element of that row)
so how will i use this file in above code???
its very difficlut to put all the edge like u did...
can u post the code in c.
You will have to write code to read the file character by character and parse accordingly.
The pseudocode may be like this:
for(every character c in first line)
{
InsertVertex(c);
}
for(every row r except first)
{
i1=1st integer in row r;
i2=2nd integer in row r;
insertEdge(i1,i2);
}