A graph is a collection of nodes (vertices) connected by edges. Itβs used to model networks like roads, social media, or even internet structure.
Example graph with nodes A, B, C, D, and E:
A / \ B C \ / D | E
#include <stdio.h> #define V 5 int main() { int graph[V][V] = { {0, 1, 1, 0, 0}, {1, 0, 0, 1, 0}, {1, 0, 0, 1, 0}, {0, 1, 1, 0, 1}, {0, 0, 0, 1, 0} }; printf("Adjacency Matrix:\\n"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { printf("%d ", graph[i][j]); } printf("\\n"); } return 0; }
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; void addEdge(struct Node* adjList[], int u, int v) { struct Node* newNode = malloc(sizeof(struct Node)); newNode->data = v; newNode->next = adjList[u]; adjList[u] = newNode; } void printGraph(struct Node* adjList[], int V) { for (int i = 0; i < V; i++) { struct Node* temp = adjList[i]; printf("Vertex %d: ", i); while (temp) { printf("β %d ", temp->data); temp = temp->next; } printf("\\n"); } } int main() { int V = 5; struct Node* adjList[5] = {NULL}; addEdge(adjList, 0, 1); addEdge(adjList, 0, 2); addEdge(adjList, 1, 3); addEdge(adjList, 2, 3); addEdge(adjList, 3, 4); printGraph(adjList, V); return 0; }
To explore nodes in a graph, use:
#include <stdio.h> #include <stdlib.h> #define SIZE 100 void bfs(int graph[][SIZE], int start, int n) { int visited[SIZE] = {0}, queue[SIZE], front = 0, rear = 0; queue[rear++] = start; visited[start] = 1; while (front < rear) { int current = queue[front++]; printf("%d ", current); for (int i = 0; i < n; i++) { if (graph[current][i] && !visited[i]) { queue[rear++] = i; visited[i] = 1; } } } }
void dfs(int graph[][SIZE], int vertex, int visited[], int n) { visited[vertex] = 1; printf("%d ", vertex); for (int i = 0; i < n; i++) { if (graph[vertex][i] && !visited[i]) { dfs(graph, i, visited, n); } } }
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!