Docsity

DFS in Directed Graphs - Lecture Notes | CS 3510, Study notes of Algorithms and Programming

Partial preview of the text

Download DFS in Directed Graphs - Lecture Notes | CS 3510 and more Study notes Algorithms and Programming in PDF only on Docsity!

Design and analysis of algorithms

Lecture 12 & 13

Edyta Szyma ´

nska

[email protected]

DFS in directed graphs

The same algorithm applies:

DFS in directed graphs

Edge classification:

  • 8, The same algorithm applies:
    • 2,
      • 3,
      • 5,
      • 14,
    • 9,
  • 13,
  • 1,
  • DFS in directed graphs 8, - 2, - 3, - 5, - 14, - 9,
    • 13,
    • 1,

DFS in directed graphs 8,

3,^

5,^

13,

1,12 B

F

C C

C C

C

Note: in the undirected case we only have tree (T) andnontree edges(B).

DFS in directed graphs 8,

2,

3,^

5,^

14, 9,

13,

1,12 B

F

C C

C C

C

Note: in the undirected case we only have tree (T) andnontree edges(B).We can classify edges based on the timestamps (

f^ [],

and

d[]).

CS3510 A, Fall 2005 – p. 2/

DFS in directed graphs - applications

Detecting cycles:

DFS in directed graphs - applications

Detecting cycles: A cycle in a directed graph is a circular path v→^0

v^1

→^...
→^

v→k^

v.^0

DFS in directed graphs - applications

Detecting cycles: A cycle in a directed graph is a circular path v→^0

v^1

→^...
→^

v→k^

v.^0 8,

2,

3,^

5,^

14, 9,

13,

1,12 B

F

C C

C C

C

A directed graph has a cycle if and only if its depth-firstsearch reveals a BACK edge.

DFS in directed graphs - applications

Detecting cycles: A cycle in a directed graph is a circular path v→^0

v^1

→^...
→^

v→k^

v.^0

A directed graph has a cycle if and only if its depth-firstsearch reveals a BACK edge. A graph without a cycle is acyclic. DAG-

directed acyclic graph

DFS in directed graphs - applications

Detecting cycles: A cycle in a directed graph is a circular path v→^0

v^1

→^...
→^

v→k^

v.^0

A directed graph has a cycle if and only if its depth-firstsearch reveals a BACK edge. A graph without a cycle is acyclic. DAG-

directed acyclic graph We can check if

G^ is a DAG using DFS, if BACK edge

detected then CYCLE, time

O(

n^ +

m)

Note: the same method works for cycles in undirected graphs, but faster O(n

)^ - why?

Topological Sort of a DAG

By a topological sorting of a directed acyclic graph weunderstand a linear ordering of vertices such that if (u, v

)^ ∈^

E^ then

u^ ≤

v^ in the ordering.

Topological Sort of a DAG

tie

undershorts

socks shoes shirt jacket

pants belt

Topological Sort of a DAG

tie

undershorts

socks shoes shirt jacket

pants belt

TOPOLOGICAL

SORT

(G)
  1. Run

DFS

(G)
  1. as

a^

vertex

u^

is^ fin-

ished (

f^ [u

]^ computed),

output it in front3. return the list