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|)?
Asked
Active
Viewed 1.0k times
6
-
1The time to insert an edge does not depend on the number of vertices or edges. The adjacency matrix has the same number of rows and columns, namely the number of vertices. Therefore, access to a given edge does not require a search. This constant behaviour is expressed as O(1). – Axel Kemper Oct 03 '17 at 16:18
-
The assumption is that your matrix is implemented using a data structure that provides constant-time access to any cell, and is not something like a 2D equivalent of a linked list. – chepner Oct 03 '17 at 16:35
-
"find the correct row in array" -- if it's an array, "finding" the row is just indexing into the array. So O(1). There is no "searching" for it, you already have the index. – harold Oct 03 '17 at 16:53
1 Answers
7
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.

Avishek Bhattacharya
- 6,534
- 3
- 34
- 53