Graph theory

advertisement
Graph theory
Prof Amir Geva
Eitan Netzer
G=(V,E)
V – Vertex•
E – Edges•
Directed Graph
Undirected Graph
Weighted Graph
Representation
BFS
Shortest distance from vertex s to each vertex v
Work on directed and undirected
First all are white
Done with vertex black
Else grey
Time and space
BFS
BFS(G,s)
for each vertex u∈V[G]-{s}
do color[u]<-white
d[u]<-∞
π [u]<-NULL
color[s]<-gray
d[s]<-0
π [s]<-NULL
Q<-{s}
while Q≠ φ
do u<-head[Q]
for each v∈Adj[u]
do if color[v] = White
then color[v]<- Gray
d[v]<- d[u]+1
π [v]<- u
Enqueue(Q,v)
Dequeue(Q)
color[u]<- Black
BFS
DFS
Search all vertexes starting at vertex s
Not have to be minimal
Time
Space
DFS(G,s)
for each vertex u∈V[G]
do color[u]<-white
π [u]<-NULL
time <- 0
for each vertex u∈V[G]
do if color[u] = white
then DFS-Visit(u)
DFS-Visit(u)
color[u]<-Gray
d[u] <- time <- time +1
for each vertex v∈Adj[u]
do if color[v] =white
then π [v]<-u
DFS-Visit(v)
color[u] = Black
f[u] <- time <- time +1
DFS
Improve weight
Relax(u,v,w)
if d[v]>d[u] + w(u,v)
then d[v]<- d[u] + w(u,v)
π [v]<- u
Dijkstra's algorithm
Find shortest path from vertex s to all other
vertexes.
Work on weighted directed and undirected.
But non negative weights
List or array
Heap
Dijkstra
Dijkstra(G,w,s)
for each vertex u∈V[G]
do d[u]<-∞
π [u]<-NULL
d[s]<-0
S <- φ
Q<-V[G]
while Q≠ φ
do u<- extract-min(Q)
S<-S ∪{u}
for each vertex v∈Adj[u] , Q
do Relax(u,v,w)
Negative example
Bellman–Ford algorithm
Find shortest path from vertex s to all other
vertexes.
Work on weighted directed can handle negative
weights
Bellman–Ford
Bellman-ford(G,w,s)
for each vertex u∈V[G]
do d[u]<-∞
π [u]<-NULL
d[s]<-0
for i <- 1 to |V(G)|-1
do for each edge (u,v)∈E[G]
do Relax(u,v,w)
for each edge (u,v)∈E[G]
do if d[v]>d[u]+w(u,v)
then return FALSE
return TRUE
Download