0
0
DSA Cprogramming~30 mins

Adjacency List vs Matrix When to Choose Which in DSA C - Build Both Approaches

Choose your learning style9 modes available
Adjacency List vs Matrix When to Choose Which
📖 Scenario: Imagine you are helping a city planner who wants to represent roads between different neighborhoods. Some neighborhoods are connected directly by roads, and some are not. You want to help the planner choose the best way to store this road information in a computer.
🎯 Goal: You will create two ways to represent the roads between neighborhoods: one using an adjacency matrix and one using an adjacency list. Then, you will decide which way is better depending on how many roads there are.
📋 What You'll Learn
Create an adjacency matrix for 4 neighborhoods with given roads
Create an adjacency list for the same 4 neighborhoods with the same roads
Count the number of roads using the adjacency matrix
Print the adjacency matrix and adjacency list to compare
💡 Why This Matters
🌍 Real World
City planners, network engineers, and social network analysts use adjacency lists and matrices to represent connections between points or people.
💼 Career
Understanding these representations helps in optimizing storage and speed when working with graphs in software development, data analysis, and network design.
Progress0 / 4 steps
1
Create an adjacency matrix for 4 neighborhoods
Create a 4x4 integer array called adjMatrix initialized with zeros. Then set the following roads (edges) to 1: from neighborhood 0 to 1, from 0 to 2, from 1 to 2, and from 2 to 3.
DSA C
Hint

Think of adjMatrix as a table where rows and columns represent neighborhoods. A 1 means a road exists.

2
Create an adjacency list for the same neighborhoods
Create an array of integer pointers called adjList with size 4. Also create an integer array called adjListSizes with size 4 to store the number of roads for each neighborhood. Initialize the adjacency list with the following roads: neighborhood 0 connects to 1 and 2, neighborhood 1 connects to 2, and neighborhood 2 connects to 3.
DSA C
Hint

Each neighborhood has a list of neighbors it connects to. Use arrays for each list and store their sizes.

3
Count the number of roads using the adjacency matrix
Create an integer variable called roadCount and set it to 0. Use a nested for loop with variables i and j to go through adjMatrix. Increase roadCount by 1 every time you find a 1 in adjMatrix[i][j].
DSA C
Hint

Look at each cell in the matrix. If it is 1, it means a road exists, so add to the count.

4
Print the adjacency matrix and adjacency list
Use printf to print the adjacency matrix in a 4x4 grid format. Then print the adjacency list by showing each neighborhood and its connected neighbors. Finally, print the total number of roads stored in roadCount.
DSA C
Hint

Print the matrix row by row, then print each neighborhood's list of neighbors. Finally, print the road count.