Reputation: 59
Is it O(n+m)
or O(nm)
? To construct it be O(nm)
and if we wanted to search, add, or delete a value it will be O(n+m)
, right? Is there anything else that would be important to consider?
Also to convert a matrix into a list it takes O(n2) and to turn a list into a matrix it is only O(nm)
correct?
Upvotes: 1
Views: 802
Reputation: 316
Remotion and search can me improved to O(logN) or average O(1) using a BST or hashing instead of a linked list to store the adjacencies, but most graph algorithms require us to scan the whole adjacency list of a vertex instead of checking individual entries, so we can usually work well with linked lists.
We can convert an adjacency list to an adjacency matrix in O(m), assuming the matrix is initially filled with zeroes. All we have to do is scan the adjacency list of every vertex, and for each edge U-V with weight W we can do matrix[U][V] = W (or matrix[U][V] = 1 if the graph is not weighted). Since we are looking to each edge exactly once (or twice if the graph is not directed), the complexity os O(m).
Upvotes: 1
Reputation: 277
i think that when you convert the list to the matrix you go:
for each vertex `O(n)`
for each neighbour `O(n)`
and that's why its also O(n^2).
if m>n, one vertex cannot have all m neighbors, and that's why you avoid O(n^3)
exemple:
a: b, c, d
b: a, c, d
c: a, b, d
d: a, b, c
full graph: O(n^2)
list size. although n = 4 and m = 6, the size is 4x4 and not 4x6.
(m = (4 * (4-1))/2 = 6 = O(n^2)
--full graph formula)
Upvotes: 0