Directed Graph를 예시로 들어보자.
Graph가 adjacency list를 사용한다고 가정하자.
WHITE: 아직 discover 되지 않은 vertex
GRAY: Discover 되었지만 아직 종료되지 않은 vertex
BLACK: Discover 되고, 해당 vertex에 adjacency한 모든 vertex가 examine 된 vertex.
: discovery time
: finishing time
DFS(G)
1. for each vertex u in G.V
2. u.color = WHITE
3. u.π = NIL
4. time = 0 //global variable
5. for each vertex u in G.V
6. if u.color == WHITE
7. DFS-VISIT(G, u)
Line 1 ~ 4: Initial setting
Line 5 ~ 7: 모든 vertex에 대해 탐색
DFS-VISIT(G, u)
1. time = time + 1
2. u.d = time
3. u.color = GRAY
4. for each vertex v in G.Adj[u]
5. if u.color == WHITE
6. v.π = u
7. DFS-VISIT(G, v)
8. u.color = BLACK
9. time = time + 1
10. u.f = time
Line 1 ~ 2: discovery time setting
Line 4 ~ 7: adjacency vertex 탐색
Line 9 ~ 10: finishing time setting
BFS와는 다르게 모든 vertex를 탐색한다.
모든 vertex가 시작 vertex가 될 수 있다.

한 vertex에 대해서 adjacency한 vertex를 탐색한다.
Adjacency한 vertex 의 = GRAY 를 세팅한다.
(2)에서의 vertex의 WHITE adjacency vertex를 확인한다.
해당 vertex에 대해 (2) ~ (3) 과정을 반복한다.
모든 Adjacency vertex를 확인했다면 처음 vertex의 다른 adjacency vertex에 대해 (2) ~ (4) 과정을 반복한다.
WHITE vertex가 남아있지 않을 때까지 (1) ~ (5) 과정을 반복한다.
모든 vertex가 BLACK이라면 종료한다.

DFS(G)
1. for each vertex u in G.V
2. u.color = WHITE
3. u.π = NIL
4. time = 0 //global variable
5. for each vertex u in G.V
6. if u.color == WHITE
7. DFS-VISIT(G, u)
DFS-VISIT(G, u)
1. time = time + 1
2. u.d = time
3. u.color = GRAY
4. for each vertex v in G.Adj[u]
5. if u.color == WHITE
6. v.π = u
7. DFS-VISIT(G, v)
8. u.color = BLACK
9. time = time + 1
10. u.f = time
Initializaion:
Graph Exploration:
DFS-VISIT:
Total Running Time:

DFS에서의 predecessor subgraph는 forest이다.
Disconnected라는 점에서 BFS와 차이가 있다.
Inclusion: Ancestor가 Descendant를 완벽하게 포함하는 경우
Disjoint: Inclusion이 아닌 경우
Overlap: Ancestor와 Descendant가 일부분만 겹치는 경우
Tree edges: forest 내에서 tree를 구성하는 edge
Back edges: self loop / Descendant to Ancestor
Forwarding edges: Ancestor to Descendant
Cross edges: 하나의 forest 내에서 서로 다른 tree의 vertex 간의 edge

edge (u, v)가 있다고 가정할 때, v의 color에 따라 edge가 분류될 수 있다.
WHITE: tree edge
GRAY: back edge
BLACK: forwarding or cross edge
Edge의 종류를 결정할 때, constant time이 소요된다.


Tree edge 와 Back edge 만 존재한다.
Forwarding edge는 Back edge가 되고, Cross edge는 Tree edge가 된다.
이미 discover 된 정점 v를 만났을 때
Total Running Time