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.
Definitions
Vertex: each element of the graph.
Edge: each connection between vertices, represented as (s, e), meaning the start and the end vertex.
In-degree: how many edges enter the vertex.
Out-degree: how many edges leave the vertex.
Directed graph: when the edges are one-way arrows, otherwise it is an undirected graph.
Cyclic graph: when the edges allow you to move in circles, otherwise it is an acyclic graph.
DAG: directed acyclic graph, a very widely used type of graph.
Topological sorting: a list of the vertices of a DAG following the hierarchy in which one connects to the next.
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