Problem:
Cycle Detection for a Directed Graph Find a cycle in a directed graph G(V, E) . Input A directed graph G is given in the following format:  |V|  |E|  s 0  t 0  s 1  t 1 : s |E|-1  t |E|-1   |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V| -1 respectively.  s i and t i represent source and target nodes of i -th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Constraints  1 ≤ |V| ≤ 100  0 ≤ |E| ≤ 1,000   s i ≠ t i  Sample Input 1 3 3
0 1
0 2
1 2 Sample Output 1 0 Sample Input 2 3 3
0 1
1 2
2 0 Sample Output 2 1

Solution (Python):
import heapq
from collections import deque
from enum import Enum
import sys
import math
from _heapq import heappush, heappop

BIG_NUM = 2000000000
MOD = 1000000007
EPS = 0.000000001


V,E = map(int,input().split())
can_visit = [[None] * V for _ in range(V)]

for i in range(V):
    for k in range(V):
        can_visit[i][k] = (i == k)

for _ in range(E):
    FROM,TO = map(int,input().split())
    can_visit[FROM][TO] = True


for mid in range(V):
    for start in range(V):
        if can_visit[start][mid] == False:
            continue
        for goal in range(V):
            if can_visit[mid][goal] == False:
                continue
            can_visit[start][goal] = True


for FROM in range(V-1):
    for TO in range(FROM+1,V):
        if can_visit[FROM][TO] == True and can_visit[TO][FROM] == True:
            print("1")
            sys.exit()

print("0")

Solution (Python):


import sys

v, e = map(int, input().split( ))

Edge = [[] for _ in range(v)]

for i in range(e):
    inpt = list(map(int, input().split( )))
    Edge[inpt[0]].append(inpt[1])

inf = 10**12


dp = [[inf for _ in range(v)] for __ in range(v)]
for i in range(v):
    for ed in Edge[i]:
        dp[i][ed] = -1
for i in range(v):
    dp[i][i] = 0
"""
・for k,for i, for jの順。for i,j,kだと別物
・dpはkによらず使い回しでよい
"""
for k in range(v):
    for j in range(v):
        for i in range(v):
            dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])

for i in range(v):
    if dp[i][i]<0:
        print(1)
        sys.exit()

print(0)

Solution (Python):
import sys

sys.setrecursionlimit(200000)


def dfs(root: int, add_duplicated=True) -> bool:
    global edges, visited, duplicated

    def body(i: int) -> bool:
        visited[i] = True
        for edge in edges[i]:
            if visited[edge]:
                if edge == root:
                    return True
                if add_duplicated:
                    duplicated.add(edge)
                continue
            if body(edge):
                return True
        return False

    return body(root)


if __name__ == "__main__":
    n, m = map(int, input().split())
    edges = [set() for _ in range(n)]  

    for _ in range(m):
        s, t = map(lambda x: int(x), input().split())
        edges[s].add(t)

    visited = [False] * n
    duplicated = set()  

    for i in range(n):
        if not visited[i]:
            if dfs(i):
                print(1)
                exit(0)
    else:
        for i in duplicated:
            visited = [False] * n
            if dfs(i, False):
                print(1)
                exit(0)
        else:
            print(0)

Solution (Python):
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l(): 
	return list(map(int,input().split()))
def m(): 
	return map(int,input().split())
def onem(): 
	return int(input())
def s(x): 
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x): 
	return " ".join(map(str,x))
def max2(x): 
	return max(map(max,x))

def Topo_sort(x,y):
	co = cl.Counter(n for m in x.values() for n in m)
	S = cl.deque([i for i in range(y) if co[i] == 0])
	while S:
		n = S.popleft()
		yield n
		for i in x[n]:
			co[i] -= 1
			if co[i] <= 0:
				S.append(i)
	if sum(co.values()) != 0:
		print(1)
		exit()
	else:
		print(0)
		exit()


v,e = m()

g = cl.defaultdict(set)

for i in range(e):
	s,t = m()
	g[s] |= {t}
a = list(Topo_sort(g,v))

Solution (Python):
l,r= [int (i) for i in input().split()]
g = [[] for i in range (l)]

for i in range(r):
    s,t=[int(j) for j in input().split()]
    g[s].append(t)
    
visited=[]
f=0

def visitd_from(index,origin):
    if visited[index]:
        return
    visited[index]= True
    for next_index in g[index]:
        if next_index ==origin:
            global f
            f=1
            return
        visitd_from(next_index, origin)

for i in range (l):
    visited =[False for i in range(l)]
    visitd_from(i,i)
    if f==1:
        break
print(f)

Solution (Python):
def tansaku(graph,v,v_num,visited,stack):
    visited[v] = True
    stack[v] = True
    for i in range(0,v_num):
        if(graph[v][i] == 1):
            if(visited[i]==False):
                if(tansaku(graph,i,v_num,visited,stack)==True):
                    return True
            elif(stack[i]==True):
                return True
    stack[v] = False
    return False

if __name__ == '__main__':
    v_num,e_num = map(int, input().split())
    graph = [ [0] * v_num for i in range(v_num)]
    for i in range(e_num):
        s,t = map(int, input().split())
        graph[s][t] = 1
    
    closed_cycle_is_found=False
    visited = [False]*v_num
    stack = [False]*v_num
    for i in range(v_num):
        for j in range(v_num):
            if(graph[i][j]==1 and visited[j]==False):
                if(tansaku(graph,j,v_num,visited,stack) == True):
                    closed_cycle_is_found=True
                    break

    if(closed_cycle_is_found):
        print("1")
    else:
        print("0")

Solution (Python):


class Stack: 
  
    def __init__(self): 
        self.items = [] 

    def isEmpty(self): 
        return len(self.items)==0  

    def push(self, item): 
        self.items.append(item) 

    def pop(self): 
        return self.items.pop()  

    def peek(self): 
        if not self.isEmpty(): 
            return self.items[len(self.items)-1] 

    def size(self): 
        return len(self.items) 



V, E = list(map(int, input().split()))

L = []

for e in range(E):
  L.append(list(map(int, input().split())))
  
innode = []
stack = Stack()

for v in range(V):
  indegree = 0
  for l in L:
    if l[1] == v:
      indegree += 1
  innode.append(indegree)
  if indegree == 0:
    stack.push(v)
count = 0  
while not stack.isEmpty():
  node = stack.pop()
  count += 1
  for i in L:
    if i[0] == node:
      innode[i[1]] -= 1
      if innode[i[1]] == 0:
        stack.push(i[1])
  if count == V:
    print(0)
    break
else:
  print(1)

Solution (Python):


v, e = map(int, input().split())
p = [[] for i in range(v)]
for i in range(e):
    s, t = list(map(int, input().split()))
    p[s].append(t)


def dfs(s):
    if visit[s] != 1:
        visit[s] = 1
        stack[s] = 1
        for t in p[s]:
            if stack[t] == 1:
                print("1")
                exit()
            else:
                dfs(t)
    stack[s] = 0


visit = [0] * v
stack = [0] * v
for i in range(v):
    dfs(i)
print("0")

Solution (Python):
def visit(j, visited, stack, Graph):
    stack[j] = 1
    vflag[j] = 1
    
    for k in Graph[j]:
        if stack[k]:
            return True
        if vflag[k]:
            continue
        if visit(k, vflag, stack, Graph):
            return True
    stack[j] = 0
    return False
 

if __name__=='__main__':
    V,E  = (int(x) for x in  input().split())
    Graph = [[] for i in range(V)]

    for i in range(E):
        s, t = (int(x)for x in input().split())
        Graph[s].append(t)
        
    vflag = [0 for i in range(V)]
    stack = [0 for i in range(V)]
    jdg = 0
    
    for j in range(V):
        if not vflag[j]:
            if visit(j, vflag, stack, Graph):
                jdg = 1
                break
    print(jdg)

Solution (Python):
import sys;

v,e=map(int, input().split());

v_l=[0]*v;
e_b=[0]*e;
e_l=[0]*e;
result=0;

for i in range(v):
    v_l[i] = 0;
for i in range(e):
    e_b[i], e_l[i] = map(int, input().split());

def DFS(u):
    global result
    global v_l
    v_l[u] = 1
    for i in range(e):
        if(e_b[i] == u):
            if(v_l[e_l[i]] == 0):
                DFS(e_l[i])
            if(v_l[e_l[i]] == 1):
                result=1
    v_l[u] = 2
    
for i in range(v):
    DFS(i)
print(result)

Solution (Python):
def input(f):
    V, E = map(int, f.readline().split())
    s = [None for _ in range(E)]
    t = [None for _ in range(E)]
    for i in range(E):
        s[i], t[i] = map(int, f.readline().split())
    return V, E, s, t

import sys

def solve(V, E, s, t):
    inf = sys.maxint
    dist = [[inf for _ in range(V)] for _ in range(V)]
    
    for i in range(E):
        dist[s[i]][t[i]] = 1
    
    for k in range(V):
        for i in range(V):
            for j in range(V):
                if i != k and k != j and dist[i][k] != inf and dist[k][j] != inf:
                        dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
    
    def has_cycle():
        for i in range(V):
            if dist[i][i] != inf:
                return 1
        return 0
    
    print(has_cycle())


with open('/dev/stdin') as f:
    solve(*input(f))

Solution (Python):
import sys

sys.setrecursionlimit(int(1e7))

n, m = map(int, input().split())

edges = {}

for i in range(m):
    s, t = map(int, input().split())
    if s not in edges:
        edges[s] = set()
    edges[s].add(t)

stack = []
visited = set()


def dfs(s: int):
    if s in stack:
        return True
    if s in visited:
        return False
    if s not in edges:
        return False

    stack.append(s)
    visited.add(s)

    for t in edges[s]:
        if dfs(t):
            return True

    stack.pop()
    return False


has_cycle = False

for i in range(n):
    if i in visited:
        continue
    if dfs(i):
        has_cycle = True

print(1 if has_cycle else 0)

Solution (Python):
def bellman_ford(num, start):
    dist = [float("inf") for i in range(num)]
    dist[start] = 0
    for i in range(num):
        update = False
        for j, k, l in adj:
            if dist[k] > dist[j] + l:
                dist[k] = dist[j] + l
                update = True
                if i == num-1:
                    return False
        if not update:
            break
    return True

v, e = map(int, input().split(" "))
adj = []
for i in range(e):
    s,t = map(int, input().split(" "))
    adj.append([s, t, -1])
for i in range(v):
    if not bellman_ford(v,i):
        print(1)
        quit()
print(0)