0% found this document useful (0 votes)
2 views

CS211 8 Graphs

The document covers the fundamentals of graphs, including definitions, types (undirected, directed, weighted), and their representations (adjacency list and matrix). It discusses graph terminology, traversal algorithms, and various applications of graphs in fields such as transportation, communication, and computer networks. Additionally, it highlights the importance of graph data structures in programming, particularly in Java.

Uploaded by

d865629w2z
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CS211 8 Graphs

The document covers the fundamentals of graphs, including definitions, types (undirected, directed, weighted), and their representations (adjacency list and matrix). It discusses graph terminology, traversal algorithms, and various applications of graphs in fields such as transportation, communication, and computer networks. Additionally, it highlights the importance of graph data structures in programming, particularly in Java.

Uploaded by

d865629w2z
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Algorithms & Data Structures

CS211

Graphs

Lectures
16, 17 & 18

Samar Alsaleh
Spring 2022
04

03 Finishing Thoughts
Summary & resources

02 Shortest Path
Problem definition, applications, & alg

Today’s 01 Graph Representation & Traversal


Adjacency lists and matrices; B/D-FS algorithms

Agenda Graph Data Structure


Basic definitions and applications
Today’s 01

Agenda Graph Data Structure


Basic definitions and applications
Graph De ni on
- Formally, a graph is an abstract data type that consists of
two sets G = (V, E), where:
- V is the set of ver ces
- E is the set of edges, connec ng pairs of ver ces
- Graph ADT captures pairwise rela onship between objects
- Graph size parameters: n = | V | , m = | E |
- In the example graph:
V = {1, 2, 3, 4, 5, 6, 7, 8}
E = {1−2, 1−3, 2−3, 2−4, 2−5, 3−5,
3−7, 3−8, 4−5, 5−6, 7−8}
n = 8, m = 11
4
fi
ti
ti
ti
ti
ti
Graph Terminology
- Connected ver ces are adjacent to one another
- Adjacent ver ces are some mes referred to as neighbors
- An edge that connects a vertex to itself is called a self-loop or sling
Complete Graph
- A path is a sequence of edges that connects two ver ces in a graph
- The length of a path in is the number of edges in the path (or the
number of ver ces minus 1)

Connected Graph
- A graph is complete if every pair of dis nct ver ces is connected
by a unique edge
- A graph is connected if there is a path from each vertex to every
other vertex
- A sub-graph of a graph is a subset of the ver ces and a subset of
Sub-Graph the edges that connects the subset of ver ces in the original graph
(of the two previous graphs)
5
ti
ti
ti
ti
ti
ti
ti
ti
ti
Graph Terminology (cont.)
- All together and some mores…

Anomalies:

connected
sup-graphs

6
Graph ADT Types

A graph can be:


- Undirected graph, if (u, v) is an edge, then there
is a path from vertex u to vertex v, and vice versa
➔ (u, v) is an undirected edge
Undirected Graph
- Directed graph (digraph), if (u, v) is an edge,
then (v, u) is not necessarily an edge
Directed Graph ➔ (u, v) is a directed edge
- Weighted graph, if (u, v) is an edge, then it has
an associated numerical value, called a weight
➔ (u, v) is a weighted edge
Weighted Graph
7
Undirected Graphs

- Given the undirected graph on the le G = (V, E)


‣ | V | = 7 ver ces ➔ V = {A, B, C, D, E, F, G}
A path of length 5: (A, B, E, C, B, D) ‣ | E | = 9 edges ➔ E = {{A, B}, {A, D}, {A, E}, {B, C}, {B, D},
{B, E}, {C, E}, {C, F}, {D, E}}
- A path in an undirected graph is an ordered sequence of
ver ces, (v0, v1, v2, . . . , vk) where {vj−1, vj} is an edge for
A path of length 4: (A, B, E, C, F )
j = 1, . . . , k
- This is called a path from v0 to vk
- The length of the path is k
- A path of length zero includes the vertex itself only - no sling
A trivial path of length 0: (A) 8
ti
ti
ft
Undirected Graphs (cont.)

- The degree of a vertex is dened as the number of


adjacent ver ces, for the graph on the top le :
- degree(A) = degree(D) = degree(C) = 3
- degree(B) = degree(E) = 4
- degree(F) = 1
- degree(G) = 0
- Those ver ces adjacent to a given vertex are its neighbors
- An undirected graph is connected if for any pair of ver ces
there is a path between them

A connected An unconnected - Two ver ces vi, vj are connected if there exists a path from
graph graph vi to vj
9
ti
ti
ti
fi
ft
ti
Direct Graph
- A directed graph, some mes referred to as a digraph,
is a graph where the edges are ordered pairs of ver ces
- This means that the edges (A, B) and (B, A) are
separate, direc onal edges in a digraph
- Edges on a digraph are associated with a direc on
- Edges are ordered pairs (vj, vk) deno ng a connec on
from vj to vk
- The edge (vj, vk) is di erent from the edge (vk, vj)
- Example: Streets are represented by digraphs
- In most cases, you can go two ways unless it is a one-
way street
10
ti
ff
ti
ti
ti
ti
ti
Direct Graph (cont.)

Example digraphs:
- The digraph on the top le has:
- Four ver ces: V = {A, B, C, D}
- Five directed edges:
E = {(A, B), (A, D), (B, C), (B, D), (D, C)}

- The digraph on the bo om le has:


- Nine ver ces: V = {v1, v2, …v9}
- These six pairs (vj, vk) are directed edges:
E = {(v1, v2), (v3, v5), (v5, v3), (v6, v9), (v8, v4), (v9, v4)}

11
ti
ti
tt
ft
ft
Direct Graph (cont.)

- A path in a digraph is either


- a sequence of directed edges that connects two
ver ces in a graph
- an ordered sequence of ver ces (v0, v1, v2, . . . , vk)
where (vj−1, vj) is an edge for j = 1, . . . , k

- The degree of a vertex must be modi ed to


In this graph: consider both cases:
- A path of length 5 is: (v1, v4, v5, v3, v5, v2) - The out-degree of a vertex is the number of
- A simple cycle of length 3 is: (v8, v4, v5, v8) ver ces which are adjacent to the given vertex
- in_degree(v1) = 0, out_degree(v1) = 2 - The in-degree of a vertex is the number of
- in_degree(v5) = 2, out_degree(v5) = 3 ver ces which this vertex is adjacent to

12
ti
ti
ti
ti
fi
Direct Graph (cont.)
- Sources and Sinks
- Ver ces with an in-degree of zero are described as sources
- Ver ces with an out-degree of zero are described as sinks
- In the top le graph:
- Sources: v1, v6, v7
- Sinks: v2, v9
- Connec vity
- A digraph is strongly connected if it contains a directed
path for every pair of ver ces {vi, vj}
- A digraph is weakly connected - or just connected - if
Strongly Weakly replacing all its directed edges with undirected edges
Connected Connected produces a connected (undirected) graph
13
ti
ti
ti
ft
ti
Direct Graph (cont.)
Cyclic Digraph Acyclic Digraph
- Acyclic Digraph (DAG)
- In a simple path, the verces and edges
are dis nct except that the rst and last
vertex may be the same
- If only the
rst and last ver ces are the
same, the path is called a cycle
More Acyclic Digraphs - A graph that has no cycles is called acyclic
- A digraph that has no cycles is called
acyclic digraph (DAG)
- Is a tree an example of DAG?! Explain!
14
ti
fi
ti
ti
fi
Weighted Graphs

- A weighted graph, some mes called a network, is a graph


with weights (or costs) associated with each edge
- A weight may represent distance, energy level, cost, etc.
- An edge is represented by a triple that includes the star ng
vertex, ending vertex, and the weight, e.g., (v3, v6, 4)
- The weight of the edge is wri en next to its ver ces
- The weight of a path in is the sum of the weights of the
edges forming the path
- For the graph on the le :
- Path (v1, v4, v6) has a weight of: 16
- Path (v2, v0, v3, v6, v5) has a weight of: 10

15
ft
ti
tt
ti
ti
Weighted Graphs (cont.)
Weighted Graph Weighted Digraph

6.4

7.5 6.8
6.7 7.3
5.9
4.1
3.2
4.7
5.4 4.5

- Weighted graphs may be either undirected or directed


- In weighted undirected graphs, both (vj, vk) and (vk, vj) have the same weight
- In weighted digraphs, the edges (vj, vk) and (vk, vj) are not necessarily of the same weight
16
Graphs Applica ons

- Electronic circuits
- Printed circuit board
- Integrated circuit
- Transporta on networks
- Highway network
- Flight network
- Computer networks
- Local area network
- Internet/Web
- Databases
- En ty-rela onship diagram
17
ti
ti
ti
ti
Graphs Applica ons (cont.)
Graph Vertix Edge
communication telephone, computer fiber optic cable
circuit gate, register, processor wire
mechanical joint rod, beam, spring
financial stock, currency transactions
transportation intersection street
internet class C network connection
game board position legal move
social relationship person friendship
neural network neuron synapse
protein network protein protein-protein interaction
molecule atom bond
18
ti
Graphs Applica ons (cont.)
- Some example applica ons of Graph:
- Finding the least congested route between two phones, given connec ons between
switching sta ons
- Determining if there is a way to get from one page to another on the WWW, just by
following links
- While driving, nd the shortest path from one city to another
- Finding the shortest path that includes all the ci es for a traveling salesperson who has to
visit a number of ci es
- Determine an ordering of courses so that you always take prerequisite courses rst

19
ti
fi
ti
ti
ti
ti
ti
fi
02

Today’s 01 Graph Representation & Traversal


Adjacency lists and matrices; B/D-FS algorithms

Agenda Graph Data Structure


Basic definitions and applications
Graph ADT
- A graph is a data structure that consists of a set of ver ces and a set of edges between
pairs of ver ces
- Java does not provide a Graph ADT
- We need to be able to do the following
- Create a graph with the speci ed number of ver ces
- Iterate through all of the ver ces in the graph
- Iterate through the ver ces that are adjacent to a speci ed vertex
- Determine whether an edge exists between two ver ces
- Determine the weight of an edge between two ver ces
- Insert an edge into the graph

21
ti
ti
ti
fi
ti
ti
ti
fi
ti
Graph Representa ons
Two representa ons of graphs are most common:
1. Adjacency List
- Edges are represented by an array of lists, called adjacency lists, where each list stores
the ver ces adjacent to a par cular vertex
2. Adjacency Matrix
- Edges are represented by a two dimensional array, called an adjacency matrix

22
ti
ti
ti
ti
Adjacency List

- Maintain vertex-indexed array of lists


1 class GraphAdjList {
2 Vertex[] vertices;
3 : : :
4 }

1 class Vertex {
2 dataType data;
3 boolean visited;
4 LinkedList neighbors;
5 : : :
6 }

23
Adjacency Matrix

- Maintain a two-dimensional V−by−V array


to represent a graph:
- For an un-weighted graph, the entries can be
Boolean values
- For a weighted graph, the matrix would
contain the weights
- Note that the adjacency matrix is:
- Symmetric in an undirected graph
➔ adj[v][w] = adj[w][v]
- Asymmetric in an directed graph
➔ adj[v][w] ≠ adj[w][v]

24
Adjacency List or Adjacency Matrix?
- In terms if worst case complexity:
Adjacency List Adjacency Matrix

Space |E| + |V | | V |2

Adding an edge 1 1
Checking if there is an
degree(v) 1
edge between v and w
Iterating over vertices
Ac vity: degree(v) |V |
adjacent to v
- Write down both adjacency matrix
and adjacency list representa ons - In prac ce, use adjacency-lists representa on
for this graph. - Algorithms based on itera ng over ver ces adjacent to v
- Which one is be er for this graph? - Real-world graphs tend to be sparse
Why? - huge number of ver ces, small average vertex degree
25
ti
ti
tt
ti
ti
ti
ti
ti
Graph Traversals
- Traversals of graphs are also called searches
- There are two main types of graph traversal algorithms:
1. Breadth- rst: behaves much like a level-order traversal of a tree
- Breadth- rst requires a queue
2. Depth- rst: behaves much like the preorder traversal of a tree
- Depth- rst requires a stack
- One di erence: there is no root node present in a graph
- Graph traversals may start at any vertex in the graph
- Let’s assume that if there is ever a choice amongst mul ple nodes, both the BFS and
DFS algorithms will choose the le -most node rst

26
fi
fi
ff
fi
fi
ft
fi
ti
Breadth-First Search (BFS)
- Conceptually, in BFS, we visit the start vexerrst, then all ver ces that are adjacent to
it next, then all nodes that can be reached by a path from the start node containing
two edges, three edges, and so on
- It’s important to note that:
- BFS computes shortest paths (fewest number of edges) from the start vertex s to all other
ver ces in a graph
- Must visit all nodes for which the shortest path from the start node is length k before we
visit any node for which the shortest path from the start node is length k + 1
- There is no special start vertex

27
ti
fi
ti
Breadth-First Search (BFS) - Algorithm
- As men oned earlier, implemen ng breadth- rst search requires a queue
- The following is an example algorithm for BFS:

1 BFS (from start vertex s)


2 Put s onto a FIFO queue, and mark s as visited
3 Repeat until the queue is empty:
4 remove the least recently added vertex v
5 for each unmarked vertex adjacent to v:
6 add to queue and mark as visited

28
ti
ti
fi
Breadth-First Search (BFS) - Example
(Input Graph)
5 5 5 5
0 1
0 4 0 4 0 4 0 4
0 1 3
3 2
3 1 6
➡ 3 1 6
➡ 3 1 6
➡ 4
3 1 6

2 7 2 7 2 7 6 2 7
7
9 8 9 8 9 8 9 8

5 5
3 2 4 6 7 8 9 5
0 4 0 4
2 4 6 7 8 9 5
➡ 4
6
6
7
3 1 6
➡ 7
8
3 1 6
➡ 8
9
9
5
5

7 8 2 7 9 2 7 5
9 5
9 8 9 8 Done! 29
Breadth-First Search (BFS) - Example (cont.)
- The following is a summary of the sequence of operaons in the previous example
a er the star ng vertex has been enqueued and visited:
Dequeued vertex Enqueued/visisted vertices Queue content Visit sequence
0 0 0
0 1, 3 1, 3 0, 1, 3
1 2, 4, 6, 7 3, 2, 4, 6, 7 0, 1, 3, 2, 4, 6, 7
3 2, 4, 6, 7 0, 1, 3, 2, 4, 6, 7
2 8, 9 4, 6, 7, 8, 9 0, 1, 3, 2, 4, 6, 7, 8, 9
4 5 6, 7, 8, 9, 5 0, 1, 3, 2, 4, 6, 7, 8, 9, 5
6 7, 8, 9, 5
7 8, 9, 5
8 9, 5
9 5
5 empty
30
ft
ti
ti
Depth-First Search (DFS)
- Conceptually, in DFS, you start at a vertex, visit it, and choose one adjacent vertex to
visit; then, choose a vertex adjacent to that vertex to visit, and so on un l you go no
further; then back up and see whether a new vertex can be found
- As men oned earlier, implemen ng depth- rst search requires a stack
- The following is an example algorithm for a recursive DFS (u lizing the recursion
stack):
1 DFS (to visit a vertex v)
2 Mark v as visited
3 Recursively visit all unmarked vertices adjacent to v

31
ti
ti
fi
ti
ti
Depth-First Search (DFS) (cont.)
- The following is an example algorithm for an itera ve DFS (u lizing a user de ned
stack ):

1 DFS (from start vertex s)


2 Put s into a LIFO stack
3 Repeat until the stack is empty:
4 remove the recently added vertex v and mark it as visited
5 for each unmarked vertex adjacent to v:
6 add to stack

- Note, the itera


ve version of DFS may act as a preorder traversal where right child is
considered before the le (VRL)

32
ti
ft
ti
ti
fi
Depth-First Search (DFS) - Example
(Input Graph)
0 0 0 1 0 3 0
0 1
1 2 1 2 1 2 0 1 2
➡ ➡ ➡
3 4 5 6 3 4 5 6 3 4 5 6 3 4 5 6

4 0 4 0 3 0 1 0
3 4 3 1 0
1 1 2 3 1 1 2 0 1 2 1 2
➡ 0 ➡ 1 0 ➡ ➡
3 4 5 6 0 3 4 5 6 3 4 5 6 3 4 5 6

33
Depth-First Search (DFS) - Example (cont.)

2 0 5 0 6 0 6 0
0 2 5 6 5
1 2 1 2 1 2 1 2
➡ ➡ 0
➡ 2
0 ➡ 5
2
2
0
3 4 5 6 3 4 5 6 3 4 5 6 0 3 4 5 6

5 0 2 0 0 0
2 0
1 2 1 2 1 2
➡ 0
➡ ➡
3 4 5 6 3 4 5 6 3 4 5 6

Done!
34
Depth-First Search (DFS) - Example (cont.)
- The following is a summary of the sequence of opera ons in the previous example
a er the rst visit func on call (note: the stack here is the recursion stack):
Pushed vertex Poped/visisted veritx Stack content Visit sequence
0 0
1 0, 1
3 0, 1, 3
4 0, 1, 3, 4
4 0, 1, 3 4
3 0, 1 4, 3
1 0 4, 3, 1
2 0, 2
5 0, 2, 5
6 0, 2, 5, 6
6 0, 2, 5 4, 3, 1, 6
5 0, 2 4, 3, 1, 6, 5
2 0 4, 3, 1, 6, 5, 2
0 empty 4, 3, 1, 6, 5, 2, 0 35
ft
fi
ti
ti
Graph Traversal Example
- Travers the following graph using both BFS and DFS:

D
H
B I
E

A G

C F

36
Graph Traversal Example (cont.)
Performing a breadth- rst traversal:

D D D
H H H
B I B I B I
E E E
A G A G A G
C F C F C F
➡ ➡
A E C B A D E C B

- Enqueue the first vertex: A, - Dequeue: A - Dequeue: B


onto the queue - Enqueue: B, C and E - Enqueue: D
- Visit Sequence: A - Visit Sequence: A, B
37
fi
Graph Traversal Example (cont.)
Performing a breadth- rst traversal (cont.):

D D D
H H H
B I B I B I
E E E
A G A G A G
C F C F C F
➡ ➡ ➡
F D E C H G F D E H G F D

- Dequeue: C - Dequeue: E - Dequeue: D


- Enqueue: F - Enqueue: G and H - Visit Sequence: A, B, C, E,
- Visit Sequence: A, B, C - Visit Sequence: A, B, C, E D

38
fi
Graph Traversal Example (cont.)
Performing a breadth- rst traversal (cont.):

D D D
H H H
B I B I B I
E E E
A G A G A G
C F C F C F
➡ ➡ ➡
H G F I H G I H

- Dequeue: F - Dequeue: G - Dequeue: H


- Visit Sequence: A, B, C, E, - Enqueue: I - Visit Sequence: A, B, C, E,
D, F - Visit Sequence: A, B, C, E, D, F, G, H
D, F, G
39
fi
Graph Traversal Example (cont.)
Performing a breadth- rst traversal (cont.):

D D
H H
B I B I
E E
A G A G
C F C F
➡ ➡
I

- Dequeue: I - The queue is empty


- Visit Sequence: A, B, C, E, - Traversal is complete!
D, F, G, H, I

40
fi
Graph Traversal Example (cont.)
Performing a recursive depth- rst traversal:

D D D
H H H
B I B I B I
E E E
A G A G A G
C F C F C F
➡ ➡
A A B A B C

- Visit the first node: A - A has an unvisited - B has an unvisited


- Visit Sequence: A neighbor, B neighbor, C
- Visit Sequence: A, B - Visit Sequence: A, B, C
41
fi
Graph Traversal Example (cont.)
Performing a recursive depth- rst traversal (cont.):

D D D
H H H
B I B I B I
E E E
A G A G A G
C F C F C F
➡ ➡ ➡
A B C D A B C D A B C D E

- C has an unvisited - D has no unvisited - C has an unvisited


neighbor, D neighbors neighbor, E
- Visit Sequence: A, B, C, D - Recurse back* to C - Visit Sequence: A, B, C, D,
- Visit Sequence: A, B, C, D E
* Note: with DFS, you recurse back until you find a node that has unvisited neighbors 42
fi
Graph Traversal Example (cont.)
Performing a recursive depth- rst traversal (cont.):

D D D
H H H
B I B I B I
E E E
A G A G A G
C F C F C F
➡ ➡ ➡
A B C D E G A B C D E G I A B C D E G I H

- E has an unvisited - G has an unvisited - I has an unvisited


neighbor, G neighbor, I neighbor, H
- Visit Sequence: A, B, C, D, - Visit Sequence: A, B, C, D, - Visit Sequence: A, B, C, D,
E, G E, G, I E, G, I, H
43
fi
Graph Traversal Example (cont.)
Performing a recursive depth- rst traversal (cont.):

D D D
H H H
B I B I B I
E E E
A G A G A G
C F C F C F
➡ ➡ ➡
A B C D E G I H A B C D E G I H F A B C D E G I H F

- H has no unvisited neighbors - C has an unvisited - We recurse back finding that


neighbor, F no other nodes have
- Recurse back to C unvisited neighbors
- Visit Sequence: A, B, C, D, - Visit Sequence: A, B, C, D,
E, G, I, H E, G, I, H, F - Traversal is complete!
44
fi
Addi onal Exercise
- Star ng from the yellow node at the top, which algorithm will visit the least number
of nodes before visi ng the red goal node?

➔ BFS will visit 5 nodes prior to the red one, while DFS will visit 10 nodes prior to the red one
➔ Remember that BFS behaves like level-order traversal of a tree while DFS like preorder traversal 45
ti
ti
ti
More Examples
- Check out more examples with interac ve visual illustra on:

<https://www.cs.usfca.edu/~galles/visualization/BFS.html> <https://www.cs.usfca.edu/~galles/visualization/DFS.html>

46
ti
ti
03

02 Shortest Path
Problem definition, applications, & alg

Today’s 01 Graph Representation & Traversal


Adjacency lists and matrices; B/D-FS algorithms

Agenda Graph Data Structure


Basic definitions and applications
Shortest Path Problem
- Finding the shortest path between two given ver ces is a common problem in graphs
- The shortest path problem is the problem of nding a path between two ver ces in a
graph such that the sum of the weights (or some mes the total number) of its
cons tuent edges is minimized

48
ti
fi
ti
ti
ti
Shortest Path Problem (cont.)
- There are two possibili es for determining the “shortest” path in a graph
1. Determine the literal shortest path between two ver ces
- That is, the least number of edges between the star ng vertex and the target vertex
- Simplest approach – a varia on of the breadth- rst traversal algorithm
2. Look for the cheapest path in a weighted graph
- Recall that in a weighted graph, the length of a path is the sum of the weights of each
of the edges in that path
- Possible approach – a min-heap or a priority queue storing (vertex, weight) pairs

49
ti
ti
fi
ti
ti
Shortest Path Applica ons

- Shortest Path has several real-world use


cases, some of which include:
- Digital mapping services
- Social networking applica ons
- Telephone network
- IP rou ng to nd open shortest path rst
- Network rou ng protocols
- Fligh ng agenda
- Designate le server
- Robot naviga on

50
ti
ti
fi
ti
fi
ti
ti
fi
ti
Shortest Path Algorithms
- The most important algorithms for solving the shortest path problem include:
- Dijkstra’s algorithm
- A* search algorithm
- Bellman-Ford algorithm
-…
- Out of which, Dijkstra’s algorithm might be the most famous one for nding the
shortest path in non-nega ve edge-weighted graphs

51
ti
fi
Dijkstra’s Algorithm

- The goal of this algorithm is to nd the shortest path and its length
- Dijkstra’s algorithm works on graphs where the weights on all
edges is posi ve
- It nds the shortest path from an ini al vertex, say s, to all the
other ver ces
- We will make the assump on that the weights on all edges is a
posi ve number
Dijkstra. Dijkstra, - Clearly, if we have nega ve ver ces, it may be possible to end up in a
recipient of the 1972
ACM Turing Award
cycle whereby each pass through the cycle decreases the total length
- Thus, a shortest length would be unde ned for such a graph
52
fi
ti
ti
ti
ti
ti
ti
fi
fi
ti
Dijkstra’s Algorithm (cont.)

- Dijkstra’s algorithm builds up a tree: there is a path from each


B node back to the star ng node
- For example, in the graph on the le , we want to nd shortest
paths from node B
- Edge values in the graph are weights
- Node values in the tree are total weights
- The arrows point in the right direc on for what we need (why?)

53
ti
ti
ft
fi
Dijkstra’s Algorithm (cont.)
- For each vertex v, Dijkstra’s algorithm keeps track of three pieces of informa on:
1. A boolean telling whether we know the shortest path to that node (ini ally true only for
the star ng node)
2. The length of the shortest path to that node known so far (0 for the star ng node)
3. The predecessor of that node along the shortest known path (unknown for all nodes)

- Using this informa on, Dijkstra’s algorithm proceeds in phases—at each step:
1. From the ver ces for which we don’t know the shortest path, pick a vertex v with the
smallest distance known so far
2. Set v’s “known” eld to true
3. For each vertex w adjacent to v, test whether its distance so far is greater than v’s
distance plus the distance from v to w; if so, set w’s distance to the new distance and w’s
predecessor to v
54
ti
ti
fi
ti
ti
ti
ti
Dijkstra’s Algorithm - Example 1

*Short video of this example

55
Dijkstra’s Algorithm - Example 1 (cont.)

56
Dijkstra’s Algorithm - Example 1 (cont.)

57
Dijkstra’s Algorithm - Example 1 (cont.)

58
Dijkstra’s Algorithm - Example 1 (cont.)

59
Dijkstra’s Algorithm - Example 1 (cont.)

60
Dijkstra’s Algorithm - Example 1 (cont.)

61
Dijkstra’s Algorithm - Example 1 (cont.)

62
Dijkstra’s Algorithm - Example 2
- Tracing Dijkstra’s algorithm star ng at vertex B:

- The resul ng vertex-weighted graph is:

63
ti
ti
More Examples
- Check out more examples with interac ve visual illustra on:

<https://www.cs.usfca.edu/~galles/visualization/Dijkstra.html>
64
ti
ti
Running Time of Graph Algorithms

65
04

03 Finishing Thoughts
Summary & resources

02 Shortest Path
Problem definition, applications, & alg

Today’s 01 Graph Representation & Traversal


Adjacency lists and matrices; B/D-FS algorithms

Agenda Graph Data Structure


Basic definitions and applications
Comics Relief :)

67
Summary
A path is a sequence of edges that connects two ver ces in a graph.
The length of a path in is the number of edges in the path.
A cycle is a path in which the rst and last ver ces are the same and none
of the edges are repeated.
A graph that has no cycles is called acyclic.
A graph is connected if there exists a path between any two ver ces.
An undirected graph is a graph where the pairings represen ng the edges
are unordered.
A digraph, some mes referred to as a digraph, is a graph where the edges
are ordered pairs of ver ces.
A weighted graph, some mes called a network, is a graph with weights
(or costs) associated with each edge.
Weighted graphs may be either undirected or directed.
68
ti
ti
ti
fi
ti
ti
ti
ti
Summary (cont.)
A path in an undirected graph is an ordered sequence of ver ces.
An undirected graph is considered connected if for any two ver ces in the
graph there is a path between them.
Path and cycles in a digraph: must move in the direc on speci ed by the
arrow.
Connectedness in a digraph: strong and weak.
Strongly Connected: If connected as a digraph - following the arrows.
Weakly connected: If the underlying undirected graph is connected (i.e. ignoring
the arrows).
The length of a path within a weighted graph is the sum of all of the edges
which make up the path.
Strategies for implemen ng graphs: Adjacency matrices and Adjacency lists.
There are two main types of graph traversal algorithms: breadth- rst
(requires a queue), and depth- rst (requires a stack).
69
ti
fi
ti
ti
fi
ti
fi
Summary (cont.)

Given a weighted digraph, we can nd the shortest distance


between two ver ces by:
star ng with a trivial path containing the ini al vertex
growing this path by always going to the next vertex which
has the shortest current path
Dijkstra's algorithm solves the single-source shortest path
problem for a non-nega ve weights graph.

70
ti
ti
ti
fi
ti
Resources & More…
Textbooks Chapters:
- Data Structures and Algorithms in Java, Ch8
- Data Structures and Algorithm Analysis in Java, Ch9
Interesting Articles & Videos:
- Graph Data Structure Intro (short video)
- Graph Data Structure 1 (short video)
- Graphs — A Visual Introduction for Beginners (article)
- How Dijkstra's Algorithm Works (video)
- Dijkstra's Shortest Path Algorithm - A Detailed and Visual
Introduction (article)
Credits:
- Some slides content and illustrations are courtesy of
Prof. Robert Sedgewick, Princeton University 71
Resources & More…

Other Resources:
- Java Software Structures - Designing and Using Data Structures,
4th edition, Lewis and Chase.
- Data Structures & Algorithms in Java, 4th edition, Drozdek.
- Data Structures and Algorithms in Java, 6th edition, Goodrich,
Tamassia and Goldwasser.
- Slides at: https://ece.uwaterloo.ca/~dwharder/aads/
Lecture_materials/
- Douglas Wilhelm Harder, Mmath, University of Waterloo.
- Slides at: http://faculty.kfupm.edu.sa/ICS/jauhar/ics202/

72
Thank You & Stay Safe
:)

You might also like