Margo
Margo

Reputation: 368

Graph as adjacency matrix time complexity

enter image description here

I don't understand why inserting an edge in adjacency matrix takes O(1) time. For example we want to add an edge from vertex 3 to 5, in oriented graph we need to change graph[2][4] to 1. In oriented do the other way round also. How can it possible be O(1), if we at least once have to go find the correct row in array, so its already O(|V|)?

Upvotes: 7

Views: 10579

Answers (1)

Avishek Bhattacharya
Avishek Bhattacharya

Reputation: 6964

In 2D array all operations are considered as O(1).

In 2D array you don't go linearly to find the find the row and the column to add the data.

Here

  a[i][[j] = k 

is an O(1) operation as you can refer the position of the array directly as index rather than going linearly.

However in Linkedlist it is true that you have to go and find the row/column by visiting all the row/column one by one.

Upvotes: 7

Related Questions