Skip to main content

Graph in DSA


Graphs and Their Representations

What is a Graph?

  • Graph: A non-linear data structure made up of vertices (nodes) and edges (connections).
  • Vertices: Points in the graph (also called nodes).
  • Edges: Connections between two vertices.
  • Non-linear: Unlike arrays or linked lists, graphs allow different paths to connect vertices.

Applications of Graphs:

  • Social Networks: People as vertices, relationships as edges.
  • Maps/Navigation: Locations as vertices, roads as edges.
  • Internet: Web pages as vertices, hyperlinks as edges.
  • Biology: Neural networks, disease spread modeling.

Graph Representations:

Graph Representation: How a graph is stored in memory. Different representations impact space and speed of operations.

Adjacency Matrix: A 2D array representing edges between vertices.

Types of Graph Representations:

1. Adjacency Matrix:

  • 2D array where cell (i, j) stores information about the edge from vertex i to vertex j.
  • Undirected Graph: Matrix is symmetric (edges go both ways).
  • Directed Graph: Matrix is not symmetric (edges have a direction).
  • Weighted Graph: Values in the matrix can represent edge weights.

Example (undirected graph):

    A B C D
    A 0 1 1 1
    B 1 0 1 1
    C 1 1 0 1
    D 1 1 1 0
    

Example (directed and weighted graph):

    A B C D
    A 0 3 0 0
    B 0 0 2 0
    C 0 0 0 4
    D 0 0 0 0
    

2. Adjacency List:

  • Array of vertices, each having a linked list of adjacent vertices.
  • Efficient for sparse graphs (many vertices with few edges).

Example (undirected graph):

    A -> B, C, D
    B -> A, C
    C -> A, B
    D -> A
    

Example (directed and weighted graph):

    A -> (B,3), (C,1)
    B -> (C,2)
    C -> (D,4)
    D -> (A,4)
    

Summary of Representations:

Adjacency Matrix:

  • Best for dense graphs.
  • Simpler to implement, but consumes more memory.
  • Can represent both directed and weighted graphs.

Adjacency List:

  • Best for sparse graphs.
  • More memory-efficient as it only stores existing edges.
  • Flexible for representing both directed and weighted graphs.

Graphs are essential for representing interconnected data and solving problems like route finding, social network analysis, and web page linking. Understanding different graph representations helps choose the right structure based on the graph's density and the required operations.

How to Assign Weights in Adjacency List:

To assign weights in an Adjacency List representation of a graph, we follow the idea that each edge between vertices (nodes) can have an associated weight (or cost). In the Adjacency List format, each vertex points to a list (or another structure) that contains its neighboring vertices and the weight of the edges connecting them.

Formula for Representing Weights in Adjacency List:

There isn't exactly a "formula" per se, but here's the general approach to represent a weighted edge in an adjacency list:

  • Adjacency List Format: Each vertex has a list (or linked list/array) of tuples, where:
  • First Element of the Tuple: The neighbor vertex (the connected vertex).
  • Second Element of the Tuple: The weight of the edge connecting the two vertices.

Example Breakdown:

Let’s take the example:

    A -> (B, 3), (C, 1)
    B -> (C, 2)
    C -> (D, 4)
    D -> (A, 4)
    

1. A -> (B, 3), (C, 1):

This means there are two edges originating from vertex A:

  • An edge from A to B with weight 3.
  • An edge from A to C with weight 1.

This can be represented as:

    A: [(B, 3), (C, 1)]
    

2. B -> (C, 2):

This means there's one edge originating from vertex B:

  • An edge from B to C with weight 2.

This can be represented as:

    B: [(C, 2)]
    

3. C -> (D, 4):

This means there's one edge originating from vertex C:

  • An edge from C to D with weight 4.

This can be represented as:

    C: [(D, 4)]
    

4. D -> (A, 4):

This means there's one edge originating from vertex D:

  • An edge from D to A with weight 4.

This can be represented as:

    D: [(A, 4)]
    

How to Assign Weights?

  • Identify the Edge: First, you need to know which two vertices are connected by the edge.
  • Determine the Weight: Then, you need the weight (or cost) of that edge. The weight is usually provided in the problem (or computed based on some logic, like distance or time).
  • Create the Tuple: For each edge, you store a tuple (neighbor, weight) in the list associated with the source vertex.

General Steps to Add Weighted Edges:

  1. Create a list or dictionary for the adjacency list.
  2. For each vertex:
    • Store a list of tuples representing its neighbors and the weights of the edges connecting them.
  3. For each edge:
    • Add a tuple (neighbor_vertex, edge_weight) to the list of the source vertex.

Example in Python Code:

    # Adjacency list representation using a dictionary
    graph = {
        'A': [('B', 3), ('C', 1)],  # A -> B with weight 3, A -> C with weight 1
        'B': [('C', 2)],             # B -> C with weight 2
        'C': [('D', 4)],             # C -> D with weight 4
        'D': [('A', 4)]              # D -> A with weight 4
    }

    # Display the adjacency list
    for vertex, edges in graph.items():
        print(f"{vertex} -> {edges}")
    

When to Use Weights in Graphs?

  • Shortest Path Algorithms: In algorithms like Dijkstra’s Algorithm or Bellman-Ford, weights are used to find the least-cost path between vertices.
  • Network Flow: In problems like maximum flow in networks, weights represent the capacity of edges.
  • Route Planning: In maps or GPS systems, weights could represent distances or travel times between locations.

Summary:

  • The weight of an edge is just a value associated with a tuple (neighbor, weight) in an adjacency list.
  • Weights can represent any cost or distance between two vertices (e.g., time, distance, cost).
  • The structure you use (Adjacency List or Matrix) depends on the size and sparsity of your graph. For sparse graphs, an Adjacency List with weighted edges is more efficient.

Summary


People are good at skipping over material they already know!

View Related Topics to







Contact Us

Name

Email *

Message *

Popular Posts

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...

📘 Overview of BER and SNR 🧮 Online Simulator for BER calculation of m-ary QAM and m-ary PSK 🧮 MATLAB Code for BER calculation of M-ary QAM, M-ary PSK, QPSK, BPSK, ... 📚 Further Reading 📂 View Other Topics on M-ary QAM, M-ary PSK, QPSK ... 🧮 Online Simulator for Constellation Diagram of m-ary QAM 🧮 Online Simulator for Constellation Diagram of m-ary PSK 🧮 MATLAB Code for BER calculation of ASK, FSK, and PSK 🧮 MATLAB Code for BER calculation of Alamouti Scheme 🧮 Different approaches to calculate BER vs SNR What is Bit Error Rate (BER)? The abbreviation BER stands for Bit Error Rate, which indicates how many corrupted bits are received (after the demodulation process) compared to the total number of bits sent in a communication process. BER = (number of bits received in error) / (total number of tran...

Constellation Diagram of ASK in Detail

A binary bit '1' is assigned a power level of E b \sqrt{E_b}  (or energy E b E_b ), while a binary bit '0' is assigned zero power (or no energy).   Simulator for Binary ASK Constellation Diagram SNR (dB): 15 Run Simulation Noisy Modulated Signal (ASK) Original Modulated Signal (ASK) Energy per bit (Eb) (Tb = bit duration): We know that all periodic signals are power signals. Now we’ll find the energy of ASK for the transmission of binary ‘1’. E b = ∫ 0 Tb (A c .cos(2П.f c .t)) 2 dt = ∫ 0 Tb (A c ) 2 .cos 2 (2П.f c .t) dt Using the identity cos 2 x = (1 + cos(2x))/2: = ∫ 0 Tb ((A c ) 2 /2)(1 + cos(4П.f c .t)) dt ...

Online Simulator for ASK, FSK, and PSK

Try our new Digital Signal Processing Simulator!   Start Simulator for binary ASK Modulation Message Bits (e.g. 1,0,1,0) Carrier Frequency (Hz) Sampling Frequency (Hz) Run Simulation Simulator for binary FSK Modulation Input Bits (e.g. 1,0,1,0) Freq for '1' (Hz) Freq for '0' (Hz) Sampling Rate (Hz) Visualize FSK Signal Simulator for BPSK Modulation ...

MATLAB Code for ASK, FSK, and PSK

📘 Overview & Theory 🧮 MATLAB Code for ASK 🧮 MATLAB Code for FSK 🧮 MATLAB Code for PSK 🧮 Simulator for binary ASK, FSK, and PSK Modulations 📚 Further Reading ASK, FSK & PSK HomePage MATLAB Code MATLAB Code for ASK Modulation and Demodulation % The code is written by SalimWireless.Com % Clear previous data and plots clc; clear all; close all; % Parameters Tb = 1; % Bit duration (s) fc = 10; % Carrier frequency (Hz) N_bits = 10; % Number of bits Fs = 100 * fc; % Sampling frequency (ensure at least 2*fc, more for better representation) Ts = 1/Fs; % Sampling interval samples_per_bit = Fs * Tb; % Number of samples per bit duration % Generate random binary data rng(10); % Set random seed for reproducibility binary_data = randi([0, 1], 1, N_bits); % Generate random binary data (0 or 1) % Initialize arrays for continuous signals t_overall = 0:Ts:(N_bits...

Coherence Bandwidth and Coherence Time

🧮 Coherence Bandwidth 🧮 Coherence Time 🧮 MATLAB Code s 📚 Further Reading For Doppler Delay or Multi-path Delay Coherence time T coh ∝ 1 / v max (For slow fading, coherence time T coh is greater than the signaling interval.) Coherence bandwidth W coh ∝ 1 / Ï„ max (For frequency-flat fading, coherence bandwidth W coh is greater than the signaling bandwidth.) Where: T coh = coherence time W coh = coherence bandwidth v max = maximum Doppler frequency (or maximum Doppler shift) Ï„ max = maximum excess delay (maximum time delay spread) Notes: The notation v max −1 and Ï„ max −1 indicate inverse proportionality. Doppler spread refers to the range of frequency shifts caused by relative motion, determining T coh . Delay spread (or multipath delay spread) determines W coh . Frequency-flat fading occurs when W coh is greater than the signaling bandwidth. Coherence Bandwidth Coherence bandwidth is...

UGC NET Electronic Science Previous Year Question Papers

Home / Engineering & Other Exams / UGC NET 2022: Previous Year Question Papers ... UGC-NET (Electronics Science, Subject code: 88) UGC Net Electronic Science Question Paper With Answer Key Download Pdf [December 2024]  UGC Net Paper 1 With Answer Key Download Pdf [Sep 2024] with full explanation UGC Net Electronic Science Question Paper With Answer Key Download Pdf [Sep 2024] UGC Net Electronic Science Question Paper With Answer Key Download Pdf [December 2023] with full explanation UGC Net Electronic Science Question Paper With Answer Key Download Pdf [June 2023] UGC Net Electronic Science Question Paper With Answer Key Download Pdf [December 2022] UGC Net Electronic Science Question Paper With Answer Key Download Pdf [June 2022] UGC Net Electronic Science Question Paper With Answer Key Download Pdf [December 2021] UGC Net Electronic Science Question With Answer Key Download Pdf [June 2020] ...

Comparisons among ASK, PSK, and FSK | And the definitions of each

📘 Comparisons among ASK, FSK, and PSK 🧮 Online Simulator for calculating Bandwidth of ASK, FSK, and PSK 🧮 MATLAB Code for BER vs. SNR Analysis of ASK, FSK, and PSK 📚 Further Reading 📂 View Other Topics on Comparisons among ASK, PSK, and FSK ... 🧮 Comparisons of Noise Sensitivity, Bandwidth, Complexity, etc. 🧮 MATLAB Code for Constellation Diagrams of ASK, FSK, and PSK 🧮 Online Simulator for ASK, FSK, and PSK Generation 🧮 Online Simulator for ASK, FSK, and PSK Constellation 🧮 Some Questions and Answers Modulation ASK, FSK & PSK Constellation MATLAB Simulink MATLAB Code Comparisons among ASK, PSK, and FSK    Comparisons among ASK, PSK, and FSK Comparison among ASK, FSK, and PSK Parameters ASK FSK PSK Variable Characteristics Amplitude Frequency ...

Constellation Diagrams of ASK, PSK, and FSK

📘 Overview of Energy per Bit (Eb / N0) 🧮 Online Simulator for constellation diagrams of ASK, FSK, and PSK 🧮 Theory behind Constellation Diagrams of ASK, FSK, and PSK 🧮 MATLAB Codes for Constellation Diagrams of ASK, FSK, and PSK 📚 Further Reading 📂 Other Topics on Constellation Diagrams of ASK, PSK, and FSK ... 🧮 Simulator for constellation diagrams of m-ary PSK 🧮 Simulator for constellation diagrams of m-ary QAM BASK (Binary ASK) Modulation: Transmits one of two signals: 0 or -√Eb, where Eb​ is the energy per bit. These signals represent binary 0 and 1.    BFSK (Binary FSK) Modulation: Transmits one of two signals: +√Eb​ ( On the y-axis, the phase shift of 90 degrees with respect to the x-axis, which is also termed phase offset ) or √Eb (on x-axis), where Eb​ is the energy per bit. These signals represent binary 0 and 1.  BPSK (Binary PSK) Modulation: Transmits one of two signals...