-
Notifications
You must be signed in to change notification settings - Fork 0
Graphs: Adjacency Matrix
Devrath edited this page Mar 10, 2024
·
5 revisions
- It is one of the ways of implementing the graph.
- It's also called 2D-array.

- Here
John
is connected toMary
,Bob
, andAlice
. - Adjacency matric is easy to implement. All we need is a 2-dimensional array.

- Here we create a new matrix with one extra row and one extra column.
- Then copy all the elements from the old matrix to a new matrix.
- There are
n-items
and add operation isn2
. -
ADD-OPERATION
isV2

- Here also, We need to create a new smaller matrix and copy the elements
- This is also
O(V2)

- Here we store the item and their index in the
HashMap
. - So we will get the position of the index of them and map the position of the edge.
- Adding the edge is also O(1).
- Removing the edge is also O(1).
Operation
->Finding all the nodes adjacent to a node or the nodes that are directly connected to that node

- First we will use the
HashTable
to find the index of theAlice
which is 3. - Then we check every item in this row to find the connected nodes.
- So finding the neighbors runs in O(V).

- The problem with adjacent matric is the size needed to allocate the nodes.
- Say there are
n-items
in the matrix ---> Thespace-complexity
isO(n2)
. - If the matrix has
1000
nodes the entries would be1000000
entries.