0
0
DSA Typescriptprogramming~3 mins

Why Adjacency Matrix Representation in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

Discover how a simple table can turn a messy friendship list into a clear, quick-to-check network!

The Scenario

Imagine you want to keep track of friendships in a group of 5 people. You try to write down who is friends with whom on a piece of paper, but it quickly becomes messy and hard to check if two people are friends.

The Problem

Writing down connections manually is slow and confusing. You might forget some friendships or make mistakes when checking if two people are connected. It's hard to find out who is friends with whom quickly.

The Solution

An adjacency matrix is like a neat table where each row and column represents a person. If two people are friends, you mark a 1 in the table at their row and column. This makes it easy to see all connections at a glance and check friendships quickly.

Before vs After
Before
const friendships = [['Alice', 'Bob'], ['Bob', 'Eve'], ['Alice', 'Eve']];
function areFriends(name1, name2) {
  for (const pair of friendships) {
    if ((pair[0] === name1 && pair[1] === name2) || (pair[1] === name1 && pair[0] === name2)) {
      return true;
    }
  }
  return false;
}
After
const adjacencyMatrix = [
  [0, 1, 0],
  [1, 0, 1],
  [0, 1, 0]
];
function areFriends(index1, index2) {
  return adjacencyMatrix[index1][index2] === 1;
}
What It Enables

With adjacency matrices, you can quickly check connections and understand the whole network easily.

Real Life Example

Social media platforms use adjacency matrices to quickly find if two users are connected or to suggest new friends.

Key Takeaways

Manual tracking of connections is slow and error-prone.

Adjacency matrix uses a simple table to represent connections clearly.

This method makes checking and managing connections fast and easy.