Problem:
Depth First Search Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered. This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source. DFS timestamps each vertex as follows:  $d[v]$ records when $v$ is first discovered.  $f[v]$ records when the search finishes examining $v$’s adjacency list.  Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:  $G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.  IDs in the adjacency list are arranged in ascending order.  The program should report the discover time and the finish time for each vertex.  When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.  The timestamp starts with 1.  Input In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format: $u$ $k$ $v_1$ $v_2$ ... $v_k$ $u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$. Output For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs. Constraints  $1 \leq n \leq 100$  Sample Input 1 4
1 1 2
2 1 4
3 0
4 1 3 Sample Output 1 1 1 8
2 2 7
3 4 5
4 3 6 Sample Input 2 6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0 Sample Output 2 1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6   This is example for Sample Input 2 (discover/finish)  Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution (Python):

"""
Created on Sun Jul  8 10:56:33 2018

@author: maezawa
"""
n = int(input())
adj = [[] for _ in range(n)]
d = [0 for _ in range(n)]
f = [0 for _ in range(n)]

for j in range(n):
    ain = list(map(int, input().split()))
    u = ain[0]
    k = ain[1]
    for i in range(k):
        adj[u-1].append(ain[i+2]-1)
    adj[u-1].sort()
    

t = 1

for j in range(n):
    if d[j] == 0:
        stack = [j]

    while stack:
        
        current = stack[-1]
        if d[current] == 0:
            d[current] = t
            t += 1
        flag = 0
        for k in adj[current]:
            if d[k] == 0:
                stack.append(k)
                flag = 1
                break
        if flag == 0:
            f[current] = t
            t += 1
            stack.pop()

    
    

for i in range(n):
    print('{} {} {}'.format(i+1, d[i], f[i]))

Solution (Python):



class Graph:
    def __init__(self, n, adj_matrix):
        self.n = n
        self.adj_matrix = adj_matrix

    def show(self):
        for _ in self.adj_matrix:
            print(*_)

    def dfs(self):
        self.states = [2] * self.n
        self.d = [None] * self.n
        self.f = [None] * self.n
        self.time = 0

        for u in range(self.n):
            if self.states[u] == 2:
                self.dfs_visit(u)

    def dfs_visit(self, u):
        self.states[u] = 1
        self.time += 1
        self.d[u] = self.time

        for v, edge in enumerate(self.adj_matrix[u]):
            if edge and self.states[v] == 2:
                self.dfs_visit(v)

        self.states[u] = 0
        self.time += 1
        self.f[u] = self.time

    def show_dfs(self, start=0):
        self.dfs()
        for i, (d, f) in enumerate(zip(self.d, self.f)):
            print(i + 1, d, f)


if __name__ == '__main__':
    n = int(input())
    adj_matrix = [[0] * n for i in range(n)]
    for i in range(n):
        for v in input().split()[2:]:
            adj_matrix[i][int(v) - 1] = 1

    g = Graph(n, adj_matrix)
    g.show_dfs()

Solution (Python):
n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
g = [0] * n

time = 0

for i in range(n):
   a = list(map(int, input().split()))
   for j in range(0, a[1], 1):
       graph[a[0] - 1][a[2 + j] - 1] = 1

def search(i):
    global time
    time = time + 1
    d[i] = time
    g[i] = 1
    for j in range(n):
        if (graph[i][j] == 1) & (g[j] == 0):
            search(j)
    time = time + 1
    f[i] = time

for i in range(n):
    if g[i] == 0:
        search(i)
[print(i+1, d[i], f[i]) for i in range(n)]

Solution (Python):
n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
g = [0] * n

time = 0

for i in range(n):
   a = list(map(int, input().split()))
   for j in range(0, a[1], 1):
       graph[a[0] - 1][a[2 + j] - 1] = 1

def search(i):
    global time
    time = time + 1
    d[i] = time
    g[i] = 1
    for j in range(n):
        if (graph[i][j] == 1) & (g[j] == 0):
            search(j)
    time = time + 1
    f[i] = time

for i in range(n):
    if g[i] == 0:
        search(i)
[print(i+1, d[i], f[i]) for i in range(n)]

Solution (Python):
def dfs(n):
    global t
    S[n] = t
    DP[n]=1
    for i in A[n][2:]:
        if not DP[i]:
            t += 1
            dfs(i)
    t += 1
    F[n] = t
n = int(input())
A = [0]*(n+1)
S = [0]*(n+1)
F = [0]*(n+1)
DP = [0]*(n+1)
for i in range(n):
    A[i+1] = [int(i) for i in input().split()]
t = 0
for i in range(1,n+1):
    if not DP[i]:
        t+=1
        dfs(i)
for i in range(1,n+1):
    tmp = "{} {} {}".format(i,S[i],F[i])
    print(tmp)

Solution (Python):
def dfs():
    tt = 0
    for u in range(N):
        if colors[u] == WHITE:
            tt = dfs_visit(u, tt)

def dfs_visit(u, tt):
    tt += 1
    colors[u] = GLAY
    d[u] = tt
    for v in range(N):
        if adjacency_list[u][v] == 1 and colors[v] == WHITE:
            tt = dfs_visit(v, tt)
    tt += 1
    colors[u] = BLACK
    f[u] = tt
    return tt


N = int(input())
adjacency_list = [[0 for j in range(N)] for i in range(N)]
for _ in range(N):
    u, k, *v = map(int, input().split())
    for i in v:
        adjacency_list[u-1][i-1] = 1

WHITE = 0
GLAY = 1
BLACK = 2
colors = [WHITE for _ in range(N)]
d = [0 for _ in range(N)]
f = [0 for _ in range(N)]

dfs()

for i in range(N):
    print("{} {} {}".format(i+1, d[i], f[i]))

Solution (Python):
def depth_search(u, t):
    t += 1
    s.append(u)
    d[u] = t
    for v in range(N):
        if adjacency_list[u][v] == 0:
            continue 
        if d[v] == 0 and v not in s:
            t = depth_search(v, t)
    t += 1
    s.pop()
    f[u] = t
    return t

N = int(input())
adjacency_list = [[0 for j in range(N)] for i in range(N)]
for _ in range(N):
    u, k, *v = input().split()
    for i in v:
        adjacency_list[int(u)-1][int(i)-1] = 1

s = []
d = [0 for _ in range(N)]
f = [0 for _ in range(N)]

t = 0
for u in range(N):
    if d[u] == 0:
        t = depth_search(u, t)

for i in range(N):
    print("{} {} {}".format(i+1, d[i], f[i]))

Solution (Python):


n = int(input())
color = ["white" for i in range(n)]
d = [[] for i in range(n)]
global t
t = 0
M = [[False for i in range(n)] for j in range(n)]
for i in range(n):
    data = list(map(int,input().split()))
    u = data[0]
    k = data[1]
    if i == 0:
        start = u
    for v in data[2:2+k]:
        M[u-1][v-1] = True


def search(u,t):
    t += 1
    color[u-1] = "gray"
    d[u-1].append(t)
    for v in range(1,n+1):
        if M[u-1][v-1] and color[v-1] == "white":
            t = search(v,t)
    color[u-1] = "black"
    t += 1
    d[u-1].append(t)
    return t

t = search(start, t)
for i in range(1,n+1):
    if color[i-1] == "white":
        t = search(i, t)

for i in range(n):
    print(i+1, d[i][0], d[i][1])

Solution (Python):



def DPS(graph,vertex,dis_time,fin_time,tmp_time):
    tmp_time[0]+=1
    dis_time[vertex]=tmp_time[0]
    for i in range(len(graph[0])):
        if(graph[vertex][i] !=0 and dis_time[i]==0):
            DPS(graph,i,dis_time,fin_time,tmp_time)
    
    tmp_time[0]+=1
    fin_time[vertex]=tmp_time[0]




n=int(input())
graph=[[0]*n for loop in range(n)]
for loop in range(n):
    tmp_ope=list(map(int,input().split()))
    for j in range(tmp_ope[1]):
        graph[tmp_ope[0]-1][tmp_ope[j+2]-1]=1


dis_time=[0]*n
fin_time=[0]*n
tmp_time=[0]
for i in range(n):
    if(dis_time[i]==0):
        DPS(graph,i,dis_time,fin_time,tmp_time)

for i in range(n):
    print(f"{i+1} {dis_time[i]} {fin_time[i]}")

Solution (Python):
n = int(input())

adj = [0]*n 

for i in range(n):
    tmp = list(map( int, input().split() ) )
    adj[tmp[0]-1] = list(map(lambda x : x - 1, tmp[2:]))

c = ['w']*n 
d = [0]*n 
f = [0]*n  
time = 0

def DFS_visit(u):
    global time
    time += 1
    d[u] = time
    c[u] = 'g'
    for v in adj[u]:
        if c[v] == 'w':
            DFS_visit(v)
    c[u] = 'b'
    time += 1
    f[u] = time
    
for u in range(n):
    if c[u] == 'w':
        DFS_visit(u)
        
        
for u in range(n):
    print(f"{u+1} {d[u]} {f[u]}")

Solution (Python):
n = int(input())
graph = [[] for _ in range(n)]
for i in range(n):
    in_list = list(map(int, input().split()))
    u = in_list[0]
    graph[u - 1] = in_list[2:]

d = [0 for _ in range(n)]
f = [0 for _ in range(n)]
time = 0

def dfs(now, prev, graph, d, f):
    if d[now] != 0:
        return d, f
    global time
    time += 1
    d[now] = time
    if not graph[now]:
        f[now] = time + 1
        time += 1
        return
    for k in graph[now]:
        if k - 1 == prev or d[k-1] !=0:
            continue
        dfs(k - 1, now, graph, d, f)
    else:
        time += 1
        f[now] = time
    return d, f



for i in range(n):
    d, f = dfs(i, 0, graph, d, f)
    print(i+1, d[i], f[i])

Solution (Python):
n = int(input())
graph = [[] for _ in range(n)]
for i in range(n):
    in_list = list(map(int, input().split()))
    u = in_list[0]
    graph[u - 1] = in_list[2:]

d = [0 for _ in range(n)]
f = [0 for _ in range(n)]
time = 0

def dfs(now, prev, graph, d, f, time):
    if d[now] != 0:
        return d, f, time
    time += 1
    d[now] = time
    if not graph[now]:
        f[now] = time + 1
        time += 1
        return d, f, time
    for k in graph[now]:
        if k - 1 == prev or d[k-1] !=0:
            continue
        _, _, time = dfs(k - 1, now, graph, d, f, time)
    else:
        time += 1
        f[now] = time
    return d, f, time



for i in range(n):
    d, f, time = dfs(i, 0, graph, d, f, time)
    print(i+1, d[i], f[i])

Solution (Python):


import sys
sys.setrecursionlimit(10 ** 9)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
INF=float('inf')

N=INT()
nodes=[[] for i in range(N)]
for i in range(N):
    l=LIST()
    u=l[0]
    l=l[2:]
    for v in l:
        nodes[u-1].append(v-1)
    nodes[u-1].sort()

ans=[[0]*2 for i in range(N)]
visited=[False]*N
time=0
def rec(u):
    if visited[u]:
        return
    visited[u]=True
    global time
    time+=1
    ans[u][0]=time
    for v in nodes[u]:
        rec(v)
    time+=1
    ans[u][1]=time

for i in range(N):
    rec(i)
for i in range(N):
    d,f=ans[i]
    print(i+1, d, f)

Solution (Python):
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1
        





d = [-1] * n
f = [-1] * n

t = 0




def dfs(u):
    global t
    
    t += 1
    d[u] = t
    for i in range(len(A[u])):
        if A[u][i] == 1 and d[i] == -1:
            dfs(i)
    t += 1
    f[u] = t
            


for i in range(n):
    if d[i] == -1:
        
        dfs(i)


for i in range(n):
    print(str(i+1), str(d[i]), str(f[i]))

Solution (Python):
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v = list(map(int, input().split()))
    for j in v:
        A[int(u)-1][int(j)-1] = 1
        

for row in A:
    msg = ' '.join(map(str, row))
    

d = [-1] * n
f = [-1] * n

t = 0












            

def get_next(u):
    for i in range(len(A[u])):
        if A[u][i] == 1 and d[i] == -1:
            return i
    return None

def dfs(u):
    global t
    s = []
    s.append(u)
    d[u] = t
    while len(s) > 0:
        p = s[-1]
        v = get_next(p)
        
        
        
        
        
        if v is not None:
            
            if d[v] == -1:
                t += 1
                d[v] = t
                s.append(v)
                
        else:
            t += 1
            
            s.pop()
            f[p] = t






    






















            


t = 0
for i in range(n):
    if d[i] == -1:
        t += 1
        
        dfs(i)


for i in range(n):
    print(str(i+1), str(d[i]), str(f[i]))

Solution (Python):

n = int(input())
A = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    u, k, *v_list = list(map(int, input().split()))
    for v in v_list:
        A[u-1][v-1] = 1


d = [0] * n
f = [0] * n
t = 0


def dfs(u):
    global t
    t += 1
    d[u] = t
    for v in range(n):
        if A[u][v] == 1 and d[v] == 0:
            dfs(v)
    t += 1
    f[u] = t


for i in range(n):
    if d[i] == 0:
        dfs(i)


for i in range(n):
    print(i+1, d[i], f[i])

Solution (Python):
n = int(input())
G = [[] for _ in range(n)]
u1 = 0
for _ in range(n):
    u, k, *v = [int(i) for i in input().split()]
    G[u - 1] = v
    if k != 0 and u1 == 0:
        u1 = u

time = 1
u = u1
D = []
out = [[i+1, 0, 0] for i in range(n)]
T = []
while True:
    if u not in D:
        out[u - 1][1] = time
        D.append(u)
        T.append(u)

    for d in D:
        if d in G[u - 1]:
            idx = G[u - 1].index(d)
            del G[u - 1][idx]

    if G[u - 1] == []:
        time += 1
        out[T.pop() - 1][2] = time
        if T == []:
            if len(D) == n:
                break
            else:
                for ni in range(n):
                    if ni + 1 not in D:
                        u = ni + 1
                        break
                time += 1
                continue
        else:
            u = T[-1]
    else:
        u = G[u - 1].pop(0)
        time += 1

for ni in range(n):
    print(*out[ni])

Solution (Python):
n = int(input())
graph = [[] for _ in range(n)]

global time
global visited 
global f_time 
global e_time 

time = 1
visited = [0 for _ in range(n)]
f_time = [0 for _ in range(n)]
e_time = [0 for _ in range(n)]

def input_graph(n):
  for _ in range(n):
    node_id, num, *v = list(map(int, input().split()))
    for i in range(num):
      graph[node_id-1].append(v[i]-1)

def dfs(node_id):
  global time
  f_time[node_id] = time
  time += 1

  for ad_node in graph[node_id]:
    if visited[ad_node] == 1:
      continue
    visited[ad_node] = 1
    dfs(ad_node)

  e_time[node_id] = time
  time += 1



if __name__ == "__main__":
  input_graph(n)
  for i in range(n):
    if visited[i] == 1:
      continue
    visited[i] = 1
    dfs(i)

  for i, (f, e) in enumerate(zip(f_time, e_time)):
    print(i+1, f, e)

Solution (Python):
def d(r):
    global n
    if t[r]:return
    n+=1
    t[r]=[r+1,n]
    for i in c[r]:d(i-1)
    n+=1
    t[r][2:]=[n]
m=input()
c=[0]*m
for _ in range(m):
    l=map(int,raw_input().split())
    c[l[0]-1]=l[2:]
n=0
t=[0]*m
for i in range(m):
    d(i)
    print " ".join(map(str,t[i]))

Solution (Python):
def depth_search(i, adj, d, f, t):
    if d[i - 1]:
        return t
    d[i - 1] = t
    t += 1
    for v in adj[i - 1]:
        t = depth_search(v, adj, d, f, t)
    f[i - 1] = t
    t += 1
    return t
n = int(input())
adj = [list(map(int, input().split()))[2:] for _ in range(n)]

d = [0] * n
f = [0] * n

t = 1
for i in range(n):
    if d[i] == 0:
        t = depth_search(i + 1, adj, d, f, t)

for i, df in enumerate(zip(d, f)):
    print(i + 1, *df)

Solution (Python):
from sys import stdin

X = [ 0 for i in range(100) ]
d = [ 0 for i in range(100) ]
f = [ 0 for i in range(100) ]
G = [[ 0 for i in range(100) ] for i in range(100)]

t = 0

def DFS(i) :
	global t
	t += 1
	d[i] = t
	for j in range(n) :
		if G[i][j] != 0 and d[j] == 0 : DFS(j)
	t += 1
	f[i] = t


n = int(input())
for i in range(n) :
	X[i] = stdin.readline().strip().split()


for i in range(n) :
	for j in range(int(X[i][1])) :
		G[int(X[i][0])-1][int(X[i][j+2])-1] = 1

for i in range(n) :
	if d[i] == 0 : DFS(i)

for i in range(n) : print(i+1,d[i],f[i])

Solution (Python):



import sys

class Graph(object):
    def __init__(self, size):
        super(Graph, self).__init__()
        self.__size = size
        self.__vertices = [None] * size

    def add_vertex(self, vertex):
        self.__vertices[vertex.id_ - 1] = vertex

    def get_vertex(self, vid):
        return self.__vertices[vid - 1]

    def depth_first_search(self):
        d = [0] * self.__size
        f = [0] * self.__size
        timer = 1
        for j in range(1, self.__size + 1):
            vtx = self.get_vertex(j)
            if not vtx.visited:
                stack = [vtx]
                d[vtx.id_ - 1] = timer
                vtx.visited = True
                timer = self.__depth_first_search(stack, timer, d, f) + 1

        for vtx in self.__vertices:
            print '%d %d %d' % (vtx.id_, d[vtx.id_ - 1], f[vtx.id_ - 1])

    def __depth_first_search(self, stack, timer, d, f):
        while len(stack) > 0:
            top = stack[-1]
            avid = top.get_next_adjacnt()
            if avid == -1:
                timer += 1
                f[top.id_ - 1] = timer
                stack.pop()
            else:
                av = self.get_vertex(avid)
                if not av.visited:
                    timer += 1
                    stack.append(av)
                    d[av.id_ - 1] = timer
                    av.visited = True
        return timer

    def __str__(self):
        str_ = ''
        for e in self.__vertices:
            str_ += '%s\n' % e
        return str_

class Vertex(object):
    def __init__(self, id_):
        super(Vertex, self).__init__()
        self.id_ = id_
        self.adjacents = []
        self.next_idx = 0
        self.visited = False

    def add_adjacent(self, avid):
        self.adjacents.append(avid)

    def get_next_adjacnt(self):
        if len(self.adjacents) == 0: return -1
        if self.next_idx < len(self.adjacents):
            val = self.adjacents[self.next_idx]
            self.next_idx += 1
            return val
        else:
            return -1

    def __str__(self):
        str_ = '%d ' % self.id_
        if len(self.adjacents) == 0:
            str_ += '0'
        else:
            str_ += '%d' % len(self.adjacents)
            for e in self.adjacents:
                str_ += ' %d' % e
        return str_



s = int(sys.stdin.readline().strip())
graph = Graph(s)
for _ in range(0, s):
    vals = [int(x) for x in sys.stdin.readline().strip().split(' ')]
    v = Vertex(vals[0])
    graph.add_vertex(v)
    if vals[1] == 0: continue
    for i in range(0, vals[1]):
        v.add_adjacent(vals[2 + i])

graph.depth_first_search()

Solution (Python):



import sys

WHITE = 0
GRAY = 1
BLACK = 2


def dbg_record(records):
    for index, record in enumerate(records):
        print("???????????????: %d" % index)
        if isinstance(record, dict):
            print("??\??????: %d" % record.get("visit", -1))
            print("?????????: %d" % record.get("leave", -1))
        else:
            print("?????????")
        print("")


def dfs(matrix):
    def internal_dfs(node_id, current_time):
        if state[node_id] == WHITE:
            
            state[node_id] = GRAY
            stack.append(node_id)
            records[node_id] = {"visit": current_time}  

            
            next_id = None
            for index in range(len(matrix)):
                if matrix[node_id][index] == 1 and state[index] == WHITE:
                    next_id = index
                    break

            if next_id is not None:
                return internal_dfs(next_id, current_time + 1)
            elif 0 < len(stack):
                
                return internal_dfs(stack.pop(), current_time + 1)
        elif state[node_id] == GRAY:
            

            
            next_id = None
            for index in range(len(matrix)):
                if matrix[node_id][index] == 1 and state[index] == WHITE:
                    next_id = index
                    break

            if next_id is not None:
                stack.append(node_id)
                return internal_dfs(next_id, current_time)
            elif 0 < len(stack):
                
                state[node_id] = BLACK
                records[node_id]["leave"] = current_time  
                return internal_dfs(stack.pop(), current_time + 1)
            else:  
                state[node_id] = BLACK
                records[node_id]["leave"] = current_time
                return current_time
        elif state[node_id] == BLACK:
            print("Black!!")

    state = [WHITE] * len(matrix)  
    records = [None] * len(matrix)  
    stack = []
    current_time = 0

    while True:
        node_id = None
        for index, record in enumerate(records):
            if record is None:
                node_id = index
                break

        if node_id is None:
            break
        else:
            current_time = internal_dfs(node_id, current_time + 1)

    return records


if __name__ == "__main__":
    
    
    
    
    
    
    
    
    
    
    lines = sys.stdin.readlines()

    
    dimension = int(lines[0])
    matrix = []
    for x in range(dimension):
        matrix.append([0] * dimension)

    
    for index, line in enumerate(lines[1:]):
        for edge in [int(x) for x in line.strip().split(" ")[2:]]:
            matrix[index][edge - 1] = 1

    records = dfs(matrix)
    for index, line in enumerate(records):
        if line is not None:
            print("%d %d %d" % (index + 1, line.get("visit", -1), line.get("leave", -1)))
        else:
            print("%d None None" % (index + 1))

Solution (Python):





import sys

WHITE = 0
GRAY = 1
BLACK = 2


def dbg_record(records):
    for index, record in enumerate(records):
        print("???????????????: %d" % index)
        if isinstance(record, dict):
            print("??\??????: %d" % record.get("visit", -1))
            print("?????????: %d" % record.get("leave", -1))
        else:
            print("?????????")
        print("")


def dfs(matrix):
    def internal_dfs(node_id, current_time):
        if state[node_id] == WHITE:
            
            state[node_id] = GRAY
            stack.append(node_id)
            records[node_id] = {"visit": current_time}  

            
            next_id = None
            for index in range(len(matrix)):
                if matrix[node_id][index] == 1 and state[index] == WHITE:
                    next_id = index
                    break

            if next_id is not None:
                return internal_dfs(next_id, current_time + 1)
            elif 0 < len(stack):
                
                return internal_dfs(stack.pop(), current_time + 1)
        elif state[node_id] == GRAY:
            

            
            next_id = None
            for index in range(len(matrix)):
                if matrix[node_id][index] == 1 and state[index] == WHITE:
                    next_id = index
                    break

            if next_id is not None:
                stack.append(node_id)
                return internal_dfs(next_id, current_time)
            elif 0 < len(stack):
                
                state[node_id] = BLACK
                records[node_id]["leave"] = current_time  
                return internal_dfs(stack.pop(), current_time + 1)
            else:  
                state[node_id] = BLACK
                records[node_id]["leave"] = current_time
                return current_time
        elif state[node_id] == BLACK:
            print("Black!!")

    state = [WHITE] * len(matrix)  
    records = [None] * len(matrix)  
    stack = []
    current_time = 0

    while True:
        node_id = None
        for index, record in enumerate(records):
            if record is None:
                node_id = index
                break

        if node_id is None:
            break
        else:
            current_time = internal_dfs(node_id, current_time + 1)

    return records


if __name__ == "__main__":
    
    
    
    
    
    
    
    
    
    
    lines = sys.stdin.readlines()

    
    dimension = int(lines[0])
    matrix = [[0 for col in range(dimension)] for row in range(dimension)]

    
    for index, line in enumerate(lines[1:]):
        for edge in [int(x) for x in line.strip().split(" ")[2:]]:
            matrix[index][edge - 1] = 1

    records = dfs(matrix)
    for index, line in enumerate(records):
        if line is not None:
            print("%d %d %d" % (index + 1, line.get("visit", -1), line.get("leave", -1)))
        else:
            print("%d None None" % (index + 1))

Solution (Python):
n = int(raw_input())

def dfs(u,t):
    global graph
    global found
    global timestamp

    if u in found: return t
    found.add(u)
    timestamp[u] = [-1,-1]
    timestamp[u][0] = t
    t += 1
    for v in graph[u]:
        t = dfs(v,t)
    timestamp[u][1] = t
    t += 1
    return t

graph = [[] for i in range(n)]
found = set()
timestamp = {}

for i in range(n):
    entry = map(int,raw_input().strip().split(' '))
    u = entry[0]
    u -= 1
    for v in entry[2:]:
        v -= 1
        graph[u].append(v)


t = 1
for i in range(n):
    t = dfs(i,t)

for i in timestamp:
    print i+1,timestamp[i][0],timestamp[i][1]

Solution (Python):


def find(A, id, V, time):
    i = id - 1
    A[i][0] = True
    A[i][1] = time
    time += 1
    for v in V[i]:
        if A[v - 1][0] == False:
            time = find(A, v, V, time)
    A[i][2] = time
    time += 1
    return time

n = int(input())

A = [[False, 0, 0] for i in range(n)]
U = []
V = []
for i in range(n):
    l = list(map(int, input().split()))
    U.append(l[0])
    V.append(l[2:])

time = 1
for u in U:
    if A[u - 1][0] == False:
        time = find(A, u, V, time)

for u in U:
    l = [u]
    l.extend(A[u - 1][1:])
    print(' '.join(map(str, l)))

Solution (Python):

def DFS(n = 1, A = [0], i = 0, d = [0], f = [0], time = 1):
    for j in range(n):
        if A[i][j] == 1 and d[j] == 0:
            time = time + 1
            d[j] = time
            time = DFS(n, A, j, d, f, time)
    time = time + 1
    f[i] = time
    return time

n = int(raw_input())
A = [0] * n
for i in range(n):
    A[i] = [0] * n

for i in range(n):
    value = map(int, raw_input().split())
    u = value[0] - 1
    k = value[1]
    nodes = value[2:]
    for j in range(k):
        v = nodes[j] - 1
        A[u][v] = 1

d = [0] * n
f = [0] * n

time = 0
for i in range(n):
    if d[i] == 0:
        time = time + 1
        d[i] = time
        time = DFS(n, A, i, d, f, time)

for i in range(n):
    print(str(i + 1) + " " + str(d[i]) + " " + str(f[i]))

Solution (Python):

def DFS(A = [0], i = 0, d = [0], f = [0], time = 1):
    for j in range(len(d)):
        if A[i][j] == 1 and d[j] == 0:
            time = time + 1
            d[j] = time
            time = DFS(A, j, d, f, time)
    time = time + 1
    f[i] = time
    return time

n = int(raw_input())
A = [0] * n
for i in range(n):
    A[i] = [0] * n

for i in range(n):
    value = map(int, raw_input().split())
    u = value[0] - 1
    k = value[1]
    nodes = value[2:]
    for j in range(k):
        v = nodes[j] - 1
        A[u][v] = 1

d = [0] * n
f = [0] * n

time = 0
for i in range(n):
    if d[i] == 0:
        time = time + 1
        d[i] = time
        time = DFS(A, i, d, f, time)

for i in range(n):
    print(str(i + 1) + " " + str(d[i]) + " " + str(f[i]))

Solution (Python):

def DFS(n = 1, i = 0, time = 1):
    for j in range(n):
        if A[i][j] == 1 and d[j] == 0:
            time = time + 1
            d[j] = time
            time = DFS(n, j, time)
    time = time + 1
    f[i] = time
    return time

n = int(raw_input())
A = [0] * n
for i in range(n):
    A[i] = [0] * n

for i in range(n):
    value = map(int, raw_input().split())
    u = value[0] - 1
    k = value[1]
    nodes = value[2:]
    for j in range(k):
        v = nodes[j] - 1
        A[u][v] = 1

d = [0] * n
f = [0] * n

time = 0
for i in range(n):
    if d[i] == 0:
        time = time + 1
        d[i] = time
        time = DFS(n, i, time)

for i in range(n):
    print(str(i + 1) + " " + str(d[i]) + " " + str(f[i]))

Solution (Python):
def DFS(s, t):
    t += 1
    flag[s] = 1
    d[s] = t
    for i in range(1, n+1):
        if G[s][i] == 1:
            if flag[i] == 0:
                DFS(i, t)
                t = f[i]
    f[s] = t + 1

n = int(raw_input())
G = [[0 for i in range(n+1)] for j in range(n+1)]
d = [0 for i in range(n+1)]
f = [0 for i in range(n+1)]

for i in range(n):
    v = map(int, raw_input().split())
    for j in range(v[1]):
        G[v[0]][v[2+j]] = 1

flag = [0 for i in range(n+1)]
for i in range(1, n+1):
    if flag[i] == 0:
        DFS(i, max(f))

for i in range(1, n+1):
    print(str(i) + " " + str(d[i]) + " " + str(f[i]))

Solution (Python):
class node:
    def __init__(self):
        self.number = 0
        self.in_time    = 0
        self.out_time   = 0
        self.link_node  = []
        self.is_serched = False

def dfs_visit(node, timer):
    node.in_time    = timer
    node.is_serched = True
    temp            = timer + 1

    for item in node.link_node:
        if item.is_serched == False:
            temp = dfs_visit(item, temp)
    node.out_time = temp
    return node.out_time + 1

n = input()
node_list = [None] * (n + 1)

for i in xrange(1, n + 1):
    node_list[i] = node()
    node_list[i].number = int(i)

for i in xrange(1, n + 1):
    line = raw_input().split()
    for node_num in line[2 : ]:
        node_list[i].link_node.append(node_list[int(node_num)])

temp = 1
for item in node_list[1 : ]:
    if item.is_serched == False:
        temp = dfs_visit(item, temp)

for item in node_list[1 : ]:
    print '%s %s %s' % (str(item.number), str(item.in_time), str(item.out_time))

Solution (Python):
n = int(raw_input())

d = [0 for i in range(n)]
f = [0 for i in range(n)]
G = [0 for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
st = [0 for i in range(n)]
t = [0]

def DFS_visit(s):
    st[s] = 1
    t[0] += 1
    d[s] = t[0]
    for e in range(n):
        if M[s][e] == 1 and st[e] == 0:
            DFS_visit(e)
    st[s] == 2
    t[0] += 1
    f[s] = t[0]

def DFS():
    for s in range(n):
        if st[s] == 0:
            DFS_visit(s)
    for s in range(n):
        print'{0} {1} {2}'.format(s+1, d[s], f[s])
    
for i in range(n):
    G = map(int, raw_input().split())
    for j in range(G[1]):
        M[G[0]-1][G[2+j]-1] = 1

DFS()