Graphs cheatsheet
Here is a list with some of the most basic forms of graphs and how to implement them. Graphs are useful when implementing search algorithms.
Edge list
Create an array with sub arrays.
Each sub array will contain 2 numbers which represent the vertices that form the edge.
It may contain a 3rd number to represent the weight.
It doesn't use much memory but the search time is long.
Adjacency matrix
Create a matrix with all the vertices x vertices. The indices of the rows and columns of the matrix will be the vertices.
Add the number 1 when 2 vertices form an edge.
Add the number 0 otherwise.
It uses a lot of memory but the search time is super fast.
Adjacency list
Create an array with sub arrays.
Each sub array's index will represent a vertex.
Fill each sub array with the vertices it forms edges with.
This one doesn't use much memory and the search time is short.
Notes
Adjacency matrix is the fastest, but uses the most memory, Adjacency list uses the least memory and Edge list is the worst in both memory and speed.
Comments
Post a Comment