Save
...
Computer Science
Data Structures
Graphs
Save
Share
Learn
Content
Leaderboard
Share
Learn
Created by
Arnav Gupta
Visit profile
Cards (15)
Graph
A set of
vertices
or nodes connected by edges or
arcs
View source
Edges
May be one-way or
two-way
in an
undirected
graph
All edges are
bidirectional
View source
Directed graph
or
digraph
A graph where the edges are all
one-way
View source
The weights in the example represent
distances
between towns
View source
A human driver can find their way from one town to another by following a
map
, but a computer needs to represent the information about
distances
and connections in a structured, numerical representation
View source
Graph
A data structure that represents a set of objects (called
vertices
or nodes) where some pairs of the objects are connected by links (called
edges
)
View source
Possible implementations of a graph
Adjacency
matrix
Adjacency
list
View source
Adjacency
matrix
A
two-dimensional
array can be used to store information about a directed or
undirected
graph
Each of the rows and columns represents a
node
A value stored in the cell at the intersection of row i, column j indicates that there is an
edge
connecting
node
i and node j
View source
In the case of an undirected graph, the
adjacency
matrix will be
symmetric
, with the same entry in (0) as in (1,0), for example
View source
An
unweighted
graph may be represented with 1s instead of
weights
, in the relevant cells
View source
Adjacency matrix
Very
convenient
to work with
Adding an edge is very
simple
View source
Adjacency matrix
Sparse
graph with many
nodes
but not many edges will leave most of the cells empty
The
larger
the graph, the more
memory space
will be wasted
Using a static
two-dimensional
array, it is harder to add or delete
nodes
View source
Adjacency list
A more
space-efficient
way to implement a
sparsely
connected graph
A list of all the
nodes
is created, and each node points to a
list
of all the adjacent nodes to which it is directly linked
The adjacency list can be implemented as a list of dictionaries, with the
key
in each dictionary being the node and the value, the
edge
weight
View source
Breadth-first
search
A graph traversal algorithm that explores all the neighboring
nodes
at the present depth before moving on to the
nodes
at the next depth level
View source
Applications of graphs
Computer networks, with
nodes
representing computers and weighted edges representing the
bandwidth
between them
Roads between towns, with edge weights representing distances,
rail fares
or
journey times
Tasks in a project, some of which have to be completed
before
others
Web pages and
links
(see Google's PageRank algorithm in Section 5)
View source