Template for Graph Creation
Graph Creation using Adjacency List
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct Node {
int vertex;
struct Node* next;
};
struct Node* adjList[MAX];
void addEdge(int u, int v) {
// Add v to u's list
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = adjList[u];
adjList[u] = newNode;
// For undirected graph, add u to v's list
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = u;
newNode->next = adjList[v];
adjList[v] = newNode;
}
Graph Creation using Adjacency Matrix
#include <stdio.h>
#define MAX 100
int adjMatrix[MAX][MAX];
void addEdge(int u, int v, int directed) {
adjMatrix[u][v] = 1;
if (!directed)
adjMatrix[v][u] = 1; // Omit for directed graph
}
Choose:
● Adjacency list for sparse graphs (space-efficient).
● Adjacency matrix for dense graphs or quick edge lookups.
Q1. BFS Traversal of an Undirected Graph
Problem Statement:
Given an undirected graph represented using an adjacency list or matrix, perform
Breadth-First Search (BFS) starting from node 0 and print the nodes in the order they are
visited.
Input Format:
● Number of vertices V and edges E
● E pairs of edges (u, v)
Expected Output:
Print the BFS traversal order from node 0.
🔹Q2. DFS Traversal of an Undirected Graph
Problem Statement:
Given an undirected graph, perform Depth-First Search (DFS) starting from node 0 and print
the visited nodes.
Input Format:
● Number of vertices V and edges E
● E pairs of edges (u, v)
Expected Output:
Print the DFS traversal order from node 0.
🔹Q3. Topological Sort of a Directed Acyclic Graph (DAG)
Problem Statement:
Given a directed acyclic graph (DAG), perform Topological Sorting using DFS and print the
topological order.
Input Format:
● Number of vertices V and edges E
● E directed edges (u → v)
Expected Output:
Print any valid topological ordering of the vertices.