Graph Theory37 sections · 1633 units
Open in Course

Method 1 - The Adjacency Matrix

The Grid Approach

I'll show you the adjacency matrix. You store a 22D array MM where M[i][j] = 1 if there is an edge from vertex ii to vertex jj, and 00 otherwise. In an undirected graph the matrix is symmetric because ii connects to jj and jj connects to ii.

Checking whether edge (u,v)(u, v) exists takes O(1)O(1) time because you read M[u][v]. The cost is space. You store V2V^2 entries, so it uses O(V2)O(V^2) space even when the graph is sparse. If you are memory bound, you will feel this immediately.