Files
G4G0-2/Data Structures/GPT Answers to Past Paper/Question 9.md
2025-01-30 09:27:31 +00:00

1.8 KiB
Executable File

Create an adjacency matrix for the following weighted undirected graph.

A-3-B 
|   | 
2   1 
|   | 
C-4-D

To create an adjacency matrix for the given weighted undirected graph, we need to follow these steps:

  1. Identify the nodes: We have 4 nodes: A, B, C, and D.
  2. Create a matrix: The matrix will be 4x4, where rows and columns represent the nodes, and the elements in the matrix represent the weights of the edges between nodes. If there's no edge between two nodes, the matrix will have a value of 0 (or infinity, depending on the context, but we'll use 0 here).
  3. Place the edge weights in the matrix: Since the graph is undirected, the matrix will be symmetric, meaning if there's an edge from node A to node B, the matrix entry at [A][B] and [B][A] will have the same value.

Graph Details:

  • A -3- B: There is an edge between A and B with weight 3.
  • A -2- C: There is an edge between A and C with weight 2.
  • B -1- D: There is an edge between B and D with weight 1.
  • C -4- D: There is an edge between C and D with weight 4.

Adjacency Matrix

Let's map the nodes to indices:

  • A = 0
  • B = 1
  • C = 2
  • D = 3

Matrix:

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

Explanation:

  • A-B has a weight of 3, so matrix[0][1] = 3 and matrix[1][0] = 3 (since the graph is undirected).
  • A-C has a weight of 2, so matrix[0][2] = 2 and matrix[2][0] = 2.
  • B-D has a weight of 1, so matrix[1][3] = 1 and matrix[3][1] = 1.
  • C-D has a weight of 4, so matrix[2][3] = 4 and matrix[3][2] = 4.

This adjacency matrix accurately represents the weighted undirected graph.