Professional Documents
Culture Documents
Lecture 7
Lecture 7
Lecture 7
⚫ A graph data structure is a collection of nodes that have data and are
connected to other nodes.
⚫ More precisely, a graph is a data structure (V, E) that consists of
⚫ A collection of vertices V
⚫ A collection of edges E, represented as ordered pairs of vertices (u,v)
⚫ In the graph,
⚫ V = {0, 1, 2, 3}
⚫ E = {(0,1), (0,2), (0,3), (1,2)}
⚫ G = {V, E}
Terminologies
// Create a node
struct node* createNode(int v) { // Add edge
struct node* newNode = malloc(sizeof(struct node)); void addEdge(struct Graph* graph, int src, int dest) {
newNode->vertex = v; // Add edge from src to dest
newNode->next = NULL; struct node* newNode = createNode(dest);
return newNode; newNode->next = graph->adjLists[src];
}
graph->adjLists[src] = newNode;
// Create graph
// Add edge from dest to src
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
newNode = createNode(src);
graph->numVertices = vertices; newNode->next = graph->adjLists[dest];
graph->adjLists = malloc(vertices * sizeof(struct node*)); graph->adjLists[dest] = newNode;
graph->visited = malloc(vertices * sizeof(int)); }
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
Implementation
int main() {
// Print the graph
struct Graph* graph = createGraph(4);
void printGraph(struct Graph* graph) {
addEdge(graph, 0, 1);
int v;
addEdge(graph, 0, 2);
for (v = 0; v < graph->numVertices; v++) {
addEdge(graph, 1, 2);
struct node* temp = graph->adjLists[v];
addEdge(graph, 2, 3);
printf("\n Adjacency list of vertex %d\n ", v);
while (temp) {
printGraph(graph);
printf("%d -> ", temp->vertex);
temp = temp->next;
DFS(graph, 2);
}
printf("\n");
return 0;
}
}
}
Breadth First Search (BFS)
if (isEmpty(q)) {
// Removing elements from queue
printf("Queue is empty");
int dequeue(struct queue* q) {
} else {
int item;
printf("\nQueue contains \n");
if (isEmpty(q)) {
for (i = q->front; i < q->rear + 1; i++) {
printf("Queue is empty"); printf("%d ", q->items[i]);
item = -1; }
} else { }
item = q->items[q->front]; }
q->front++; int main() {
if (q->front > q->rear) { struct Graph* graph = createGraph(6);
printf("Resetting queue "); addEdge(graph, 0, 1);
q->front = q->rear = -1; addEdge(graph, 0, 2);
} addEdge(graph, 1, 2);
} addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
return item;
addEdge(graph, 2, 4);
}
addEdge(graph, 3, 4);
// Print the queue
bfs(graph, 0);
void printQueue(struct queue* q) {
return 0;
int i = q->front;
}
Thank You