Graphs overview
Graphs overview
1. Definition
2. Basic Terminology
3. Graph Types
4. Graph Representations
Static Representation
● Adjacency Matrix: 2D array where matrix[i][j] is 1 if there's an edge between i
and j.
○ Space Complexity: O(V2)O(V^2)O(V2).
○ Best For: Dense graphs.
● Adjacency List: Array of lists where list[i] contains all neighbors of vertex i.
○ Space Complexity: O(V+E)O(V + E)O(V+E).
○ Best For: Sparse graphs.
Dynamic Representation
● Using data structures like vector or map for adjacency lists, which grow dynamically.
Adjacency Matrix
cpp
Copy code
#include <iostream>
using namespace std;
#define V 5
int main() {
int graph[V][V] = { {0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 1, 1},
{0, 1, 1, 0, 1},
{1, 0, 1, 1, 0} };
printMatrix(graph);
return 0;
}
Adjacency List
cpp
Copy code
#include <iostream>
#include <vector>
using namespace std;
int main() {
int V = 5;
vector<int> adj[V];
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
printGraph(adj, V);
return 0;
}
6. Graph Searching Algorithms
● Queue-based.
● Explores all neighbors before moving to the next level.
8. Applications of Graphs
Adjacency Matrix
cpp
Copy code
#include <iostream>
int main() {
int V = 5;
// Example graph
matrix[0][1] = 1; matrix[0][4] = 1;
matrix[2][1] = 1; matrix[2][3] = 1;
printAdjMatrix(matrix, V);
delete[] matrix;
return 0;
Adjacency List
cpp
Copy code
#include <iostream>
struct Node {
int data;
Node *next;
};
adjList[u] = newNode;
adjList[v] = newNode;
while (temp) {
temp = temp->next;
}
int main() {
int V = 5;
addEdge(adjList, 0, 1);
addEdge(adjList, 0, 4);
addEdge(adjList, 1, 2);
addEdge(adjList, 1, 3);
addEdge(adjList, 1, 4);
addEdge(adjList, 2, 3);
addEdge(adjList, 3, 4);
printAdjList(adjList, V);
temp = temp->next;
delete delNode;
delete[] adjList;
return 0;
BFS
cpp
Copy code
#include <iostream>
#include <queue>
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
q.pop();
visited[i] = true;
q.push(i);
delete[] visited;
int main() {
int V = 5;
int **matrix = new int *[V];
matrix[0][1] = 1; matrix[0][4] = 1;
matrix[2][1] = 1; matrix[2][3] = 1;
bfs(matrix, V, 0);
delete[] matrix;
return 0;
DFS
cpp
Copy code
#include <iostream>
visited[node] = true;
delete[] visited;
int main() {
int V = 5;
matrix[0][1] = 1; matrix[0][4] = 1;
matrix[2][1] = 1; matrix[2][3] = 1;
dfs(matrix, V, 0);
delete[] matrix;
return 0;
int main() {
int V = 5;
int **graph = new int *[V];
for (int i = 0; i < V; i++) {
graph[i] = new int[V]();
}
// Example graph
graph[0][1] = 10; graph[0][4] = 5;
graph[1][2] = 1; graph[1][4] = 2;
graph[2][3] = 4;
graph[3][0] = 7; graph[3][2] = 6;
graph[4][1] = 3; graph[4][2] = 9; graph[4][3] = 2;
dijkstra(graph, V, 0);
return 0;
}
4. Floyd-Warshall Algorithm
cpp
Copy code
#include <iostream>
#include <climits>
using namespace std;
int main() {
int V = 4;
int **graph = new int *[V];
for (int i = 0; i < V; i++) {
graph[i] = new int[V];
for (int j = 0; j < V; j++) {
graph[i][j] = (i == j) ? 0 : INT_MAX;
}
}
graph[0][1] = 3; graph[0][3] = 5;
graph[1][0] = 2; graph[1][3] = 4;
graph[2][1] = 1;
graph[3][2] = 2;
floydWarshall(graph, V);
return 0;
}
delete[] visited;
}
int main() {
int V = 6;
int **graph = new int *[V];
for (int i = 0; i < V; i++) {
graph[i] = new int[V]();
}
graph[5][2] = 1; graph[5][0] = 1;
graph[4][0] = 1; graph[4][1] = 1;
graph[2][3] = 1;
graph[3][1] = 1;
topologicalSort(graph, V);
return 0;
}
Bridges in a Graph
cpp
Copy code
#include <iostream>
#include <cstring>
using namespace std;
void dfsBridge(int **graph, int V, int u, int parent, int *disc, int
*low, bool *visited) {
static int time = 0;
visited[u] = true;
disc[u] = low[u] = ++time;
delete[] disc;
delete[] low;
delete[] visited;
}
int main() {
int V = 5;
int **graph = new int *[V];
for (int i = 0; i < V; i++) {
graph[i] = new int[V]();
}
// Example graph
graph[0][1] = 1; graph[1][0] = 1;
graph[1][2] = 1; graph[2][1] = 1;
graph[1][3] = 1; graph[3][1] = 1;
graph[3][4] = 1; graph[4][3] = 1;
findBridges(graph, V);
return 0;
}
delete[] disc;
delete[] low;
delete[] visited;
delete[] ap;
}
int main() {
int V = 5;
int **graph = new int *[V];
for (int i = 0; i < V; i++) {
graph[i] = new int[V]();
}
// Example graph
graph[0][1] = 1; graph[1][0] = 1;
graph[1][2] = 1; graph[2][1] = 1;
graph[1][3] = 1; graph[3][1] = 1;
graph[3][4] = 1; graph[4][3] = 1;
findArticulationPoints(graph, V);
return 0;
}
delete[] parent;
delete[] key;
delete[] mstSet;
}
int main() {
int V = 5;
int **graph = new int *[V];
for (int i = 0; i < V; i++) {
graph[i] = new int[V];
}
// Example graph
graph[0][1] = 2; graph[0][3] = 6;
graph[1][0] = 2; graph[1][2] = 3; graph[1][3] = 8; graph[1][4] =
5;
graph[2][1] = 3; graph[2][4] = 7;
graph[3][0] = 6; graph[3][1] = 8; graph[3][4] = 9;
graph[4][1] = 5; graph[4][2] = 7; graph[4][3] = 9;
primMST(graph, V);
return 0;
}
The N-Queens Problem is a classic example of graph coloring, where each queen represents a
node, and we aim to "color" nodes (place queens) such that no two queens threaten each other.
return true;
}
board[i][col] = 0; // Backtrack
}
}
void solveNQueens() {
int board[N][N] = {0};
if (!solveNQueensUtil(board, 0)) {
cout << "No solution exists." << endl;
} else {
printSolution(board);
}
}
int main() {
solveNQueens();
return 0;
}
You can modify the value of N to solve for different sizes of chessboards!
Given Tasks:
C++ Code:
cpp
Copy code
#include <iostream>
using namespace std;
cout << "Total edges in the graph: " << totalEdges << endl;
cout << "Maximum degree of any node: " << maxDegree << endl;
}
int main() {
int n = 4; // Number of nodes
int graph[MAX][MAX] = {
{0, 1, 0, 0},
{0, 0, 1, 1},
{0, 0, 0, 1},
{0, 0, 0, 0}
};
analyzeGraph(graph, n);
return 0;
}
Q5(b): Depth First Search (DFS) and Breadth First Search (BFS)
Explanation:
● DFS uses a stack (or recursion) to explore as deep as possible before backtracking.
● BFS uses a queue to explore all neighbors of a node level by level.
C++ Code:
cpp
Copy code
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
if (!visited[node]) {
visited[node] = true;
cout << node << " ";
int main() {
int n = 4; // Number of nodes
int graph[MAX][MAX] = {
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1},
{0, 0, 0, 0}
};
DFS(graph, n, 0);
BFS(graph, n, 0);
return 0;
}
Input:
Edge list representation like {{a, b}, {b, c}, {a, c}}.
Output:
C++ Code:
cpp
Copy code
#include <iostream>
using namespace std;
int main() {
int edges[][2] = {
{0, 1}, {1, 2}, {0, 2}
};
int edgeCount = 3;
int n = 3; // Number of nodes
int adjList[MAX][MAX];
edgeListToAdjList(edges, edgeCount, adjList, n);
printAdjList(adjList, n);
return 0;
}
(a) Adjacency Matrix, Incidence Matrix, and Adjacency List Comparison
1. Adjacency Matrix:
○ A 2D matrix of size N×NN \times NN×N, where NNN is the number of vertices.
○ Entry adj[i][j]=1adj[i][j] = 1adj[i][j]=1 if there's an edge from vertex iii to jjj;
otherwise 000.
○ Memory Required: O(N2)O(N^2)O(N2).
2. Incidence Matrix:
○ A 2D matrix of size N×MN \times MN×M, where MMM is the number of edges.
○ Entry inc[i][j]=1inc[i][j] = 1inc[i][j]=1 if vertex iii is connected to edge jjj.
○ Memory Required: O(N×M)O(N \times M)O(N×M).
3. Adjacency List:
○ An array of lists where each index represents a vertex, and the list contains all
adjacent vertices.
○ Memory Required: O(N+M)O(N + M)O(N+M), since storing edges is
proportional to the number of edges MMM, and vertices NNN.
Traversal Methods:
#include <iostream>
#include <queue>
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
q.pop();
cout << char(node + 'a') << " "; // Convert to letter representation
visited[i] = true;
q.push(i);
int main() {
int adjMatrix[6][6] = {
{0, 1, 0, 0, 0, 0},
{1, 0, 6, 8, 0, 2},
{0, 6, 0, 7, 0, 0},
{0, 8, 7, 0, 9, 2},
{0, 0, 0, 9, 0, 1},
{0, 2, 0, 2, 1, 0}
};
return 0;
(c) Shortest Path Using Dijkstra's Algorithm (with adjacency matrix and
arrays)
C++ Code:
cpp
Copy code
#include <iostream>
#include <climits>
dist[i] = INT_MAX;
visited[i] = false;
minDist = dist[i];
u = i;
visited[u] = true;
}
}
cout << "Shortest paths from node " << char(source + 'a') <<
":\n";
cout << "To node " << char(i + 'a') << " -> " << (dist[i] ==
INT_MAX ? -1 : dist[i]) << "\n";
int main() {
int graph[6][6] = {
{INT_MAX, 8, 7, 0, 9, 2},
{INT_MAX, 2, INT_MAX, 2, 1, 0}
};
Explanation:
1. BFS Implementation:
○ Uses an adjacency matrix (adjMatrix) of size n×nn \times nn×n and a queue
for traversal.
○ A visited array ensures each node is processed only once.
2. Dijkstra’s Algorithm:
○ Uses arrays for dist (distance from source) and visited (to mark processed
nodes).
○ For each node, it finds the minimum distance unvisited node and updates the
distances of its neighbors.