Banana-Leopard/TASTY huggingface dataset:
# Python3 code to find minimum steps to reach
# to specific cell in minimum moves by Knight
 
 
class cell:
 
    def __init__(self, x=0, y=0, dist=0):
        self.x = x
        self.y = y
        self.dist = dist
 
# checks whether given position is
# inside the board
 
 
def isInside(x, y, N):
    if (x >= 1 and x <= N and
            y >= 1 and y <= N):
        return True
    return False
 
# Method returns minimum step to reach
# target position
 
 
def minStepToReachTarget(knightpos,
                         targetpos, N):
 
    # all possible movements for the knight
    dx = [2, 2, -2, -2, 1, 1, -1, -1]
    dy = [1, -1, 1, -1, 2, -2, 2, -2]
 
    queue = []
 
    # push starting position of knight
    # with 0 distance
    queue.append(cell(knightpos[0], knightpos[1], 0))
 
    # make all cell unvisited
    visited = [[False for i in range(N + 1)]
               for j in range(N + 1)]
 
    # visit starting state
    visited[knightpos[0]][knightpos[1]] = True
 
    # loop until we have one element in queue
    while(len(queue) > 0):
 
        t = queue[0]
        queue.pop(0)
 
        # if current cell is equal to target
        # cell, return its distance
        if(t.x == targetpos[0] and
           t.y == targetpos[1]):
            return t.dist
 
        # iterate for all reachable states
        for i in range(8):
 
            x = t.x + dx[i]
            y = t.y + dy[i]
 
            if(isInside(x, y, N) and not visited[x][y]):
                visited[x][y] = True
                queue.append(cell(x, y, t.dist + 1))
 
 
# Driver Code
if __name__ == '__main__':
    N = 30
    knightpos = [1, 1]
    targetpos = [30, 30]
 
    # Function call
    print(minStepToReachTarget(knightpos,
                               targetpos, N))
 
# This code is contributed by
# Kaustav kumar Chanda

Time complexity: quadratic
Space complexity: quadratic
# Python program to detect cycle
# in a graph
 
from collections import defaultdict
 
class Graph():
    def __init__(self,vertices):
        self.graph = defaultdict(list)
        self.V = vertices
 
    def addEdge(self,u,v):
        self.graph[u].append(v)
 
    def isCyclicUtil(self, v, visited, recStack):
 
        # Mark current node as visited and
        # adds to recursion stack
        visited[v] = True
        recStack[v] = True
 
        # Recur for all neighbours
        # if any neighbour is visited and in
        # recStack then graph is cyclic
        for neighbour in self.graph[v]:
            if visited[neighbour] == False:
                if self.isCyclicUtil(neighbour, visited, recStack) == True:
                    return True
            elif recStack[neighbour] == True:
                return True
 
        # The node needs to be popped from
        # recursion stack before function ends
        recStack[v] = False
        return False
 
    # Returns true if graph is cyclic else false
    def isCyclic(self):
        visited = [False] * (self.V + 1)
        recStack = [False] * (self.V + 1)
        for node in range(self.V):
            if visited[node] == False:
                if self.isCyclicUtil(node,visited,recStack) == True:
                    return True
        return False
 
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
if g.isCyclic() == 1:
    print "Graph contains cycle"
else:
    print "Graph doesn't contain cycle"
 
# Thanks to Divyanshu Mehta for contributing this code

Time complexity: linear
Space complexity: linear
# Python Program to detect cycle in an undirected graph
from collections import defaultdict
 
# This class represents a undirected
# graph using adjacency list representation
 
 
class Graph:
 
    def __init__(self, vertices):
 
        # No. of vertices
        self.V = vertices  # No. of vertices
 
        # Default dictionary to store graph
        self.graph = defaultdict(list)
 
    # Function to add an edge to graph
    def addEdge(self, v, w):
 
        # Add w to v_s list
        self.graph[v].append(w)
 
        # Add v to w_s list
        self.graph[w].append(v)
 
    # A recursive function that uses
    # visited[] and parent to detect
    # cycle in subgraph reachable from vertex v.
    def isCyclicUtil(self, v, visited, parent):
 
        # Mark the current node as visited
        visited[v] = True
 
        # Recur for all the vertices
        # adjacent to this vertex
        for i in self.graph[v]:
 
            # If the node is not
            # visited then recurse on it
            if visited[i] == False:
                if(self.isCyclicUtil(i, visited, v)):
                    return True
            # If an adjacent vertex is
            # visited and not parent
            # of current vertex,
            # then there is a cycle
            elif parent != i:
                return True
 
        return False
 
    # Returns true if the graph
    # contains a cycle, else false.
 
    def isCyclic(self):
 
        # Mark all the vertices
        # as not visited
        visited = [False]*(self.V)
 
        # Call the recursive helper
        # function to detect cycle in different
        # DFS trees
        for i in range(self.V):
 
            # Don't recur for u if it
            # is already visited
            if visited[i] == False:
                if(self.isCyclicUtil
                   (i, visited, -1)) == True:
                    return True
 
        return False
 
 
# Create a graph given in the above diagram
g = Graph(5)
g.addEdge(1, 0)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(0, 3)
g.addEdge(3, 4)
 
if g.isCyclic():
    print("Graph contains cycle")
else:
    print("Graph doesn't contain cycle ")
g1 = Graph(3)
g1.addEdge(0, 1)
g1.addEdge(1, 2)
 
 
if g1.isCyclic():
    print("Graph contains cycle")
else:
    print("Graph doesn't contain cycle ")
 
# This code is contributed by Neelam Yadav

Time complexity: linear
Space complexity: linear
# Python program to detect cycle in
# a directed graph
 
from collections import defaultdict
 
class Graph():
    def __init__(self, V):
        self.V = V
        self.graph = defaultdict(list)
 
    def addEdge(self, u, v):
        self.graph[u].append(v)
 
    def DFSUtil(self, u, color):
        # GRAY :  This vertex is being processed (DFS
        #         for this vertex has started, but not
        #         ended (or this vertex is in function
        #         call stack)
        color[u] = "GRAY"
 
        for v in self.graph[u]:
 
            if color[v] == "GRAY":
                return True
 
            if color[v] == "WHITE" and self.DFSUtil(v, color) == True:
                return True
 
        color[u] = "BLACK"
        return False
 
    def isCyclic(self):
        color = ["WHITE"] * self.V
 
        for i in range(self.V):
            if color[i] == "WHITE":
                if self.DFSUtil(i, color) == True:
                    return True
        return False
 
# Driver program to test above functions
 
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Graph contains cycle" if g.isCyclic() == True\
                             else "Graph doesn't contain cycle")
                              
# This program is contributed by Divyanshu Mehta                            

Time complexity: linear
Space complexity: linear
# Python3 program to implement Union-Find
# with union by rank and path compression.
 
# set parent of every node to itself
# and size of node to one
def initialize(n):
    global Arr, size
    for i in range(n + 1):
        Arr[i] = i
        size[i] = 1
 
# Each time we follow a path, find
# function compresses it further
# until the path length is greater
# than or equal to 1.
def find(i):
    global Arr, size
     
    # while we reach a node whose
    # parent is equal to itself
    while (Arr[i] != i):
        Arr[i] = Arr[Arr[i]] # Skip one level
        i = Arr[i] # Move to the new level
    return i
 
# A function that does union of two
# nodes x and y where xr is root node
# of x and yr is root node of y
def _union(xr, yr):
    global Arr, size
    if (size[xr] < size[yr]): # Make yr parent of xr
        Arr[xr] = Arr[yr]
        size[yr] += size[xr]
    else: # Make xr parent of yr
        Arr[yr] = Arr[xr]
        size[xr] += size[yr]
 
# The main function to check whether
# a given graph contains cycle or not
def isCycle(adj, V):
    global Arr, size
     
    # Iterate through all edges of graph,
    # find nodes connecting them.
    # If root nodes of both are same,
    # then there is cycle in graph.
    for i in range(V):
        for j in range(len(adj[i])):
            x = find(i) # find root of i
            y = find(adj[i][j]) # find root of adj[i][j]
 
            if (x == y):
                return 1 # If same parent
            _union(x, y) # Make them connect
    return 0
 
# Driver Code
MAX_VERTEX = 101
 
# Arr to represent parent of index i
Arr = [None] * MAX_VERTEX
 
# Size to represent the number of nodes
# in subgraph rooted at index i
size = [None] * MAX_VERTEX
 
V = 3
 
# Initialize the values for array
# Arr and Size
initialize(V)
 
# Let us create following graph
#     0
# | \
# | \
# 1-----2
 
# Adjacency list for graph
adj = [[] for i in range(V)]
 
adj[0].append(1)
adj[0].append(2)
adj[1].append(2)
 
# call is_cycle to check if it
# contains cycle
if (isCycle(adj, V)):
    print("Graph contains Cycle.")
else:
    print("Graph does not contain Cycle.")
 
# This code is contributed by PranchalK

Time complexity: logn
Space complexity: constant
# Python3 program to find number of magical
# indices in the given array.
 
# Function to count number of magical
# indices.
def solve(A, n) :
 
    cnt = 0
     
    # Array to store parent node of
    # traversal.
    parent = [None] * (n + 1)
     
    # Array to determine whether current node
    # is already counted in the cycle.
    vis = [None] * (n + 1)
     
    # Initialize the arrays.
    for i in range(0, n+1):
        parent[i] = -1
        vis[i] = 0       
     
    for i in range(0, n):
        j = i
     
        # Check if current node is already
        # traversed or not. If node is not
        # traversed yet then parent value
        # will be -1.
        if (parent[j] == -1) :
     
            # Traverse the graph until an
            # already visited node is not
            # found.
            while (parent[j] == -1) :
                parent[j] = i
                j = (j + A[j] + 1) % n
     
            # Check parent value to ensure
            # a cycle is present.
            if (parent[j] == i) :
     
                # Count number of nodes in
                # the cycle.
                while (vis[j]==0) :
                    vis[j] = 1
                    cnt = cnt + 1
                    j = (j + A[j] + 1) % n
    return cnt
 
# Driver code    
A = [ 0, 0, 0, 2 ]
n = len(A)
print (solve(A, n))
 
# This code is contributed by Manish Shaw
# (manishshaw1)

Time complexity: linear
Space complexity: linear
# Python program to print topological sorting of a DAG
from collections import defaultdict
 
# Class to represent a graph
 
 
class Graph:
    def __init__(self, vertices):
        self.graph = defaultdict(list)  # dictionary containing adjacency List
        self.V = vertices  # No. of vertices
 
    # function to add an edge to graph
    def addEdge(self, u, v):
        self.graph[u].append(v)
 
    # A recursive function used by topologicalSort
    def topologicalSortUtil(self, v, visited, stack):
 
        # Mark the current node as visited.
        visited[v] = True
 
        # Recur for all the vertices adjacent to this vertex
        for i in self.graph[v]:
            if visited[i] == False:
                self.topologicalSortUtil(i, visited, stack)
 
        # Push current vertex to stack which stores result
        stack.append(v)
 
    # The function to do Topological Sort. It uses recursive
    # topologicalSortUtil()
    def topologicalSort(self):
        # Mark all the vertices as not visited
        visited = [False]*self.V
        stack = []
 
        # Call the recursive helper function to store Topological
        # Sort starting from all vertices one by one
        for i in range(self.V):
            if visited[i] == False:
                self.topologicalSortUtil(i, visited, stack)
 
        # Print contents of the stack
        print(stack[::-1])  # return list in reverse order
 
 
# Driver Code
if __name__ == '__main__':
    g = Graph(6)
    g.addEdge(5, 2)
    g.addEdge(5, 0)
    g.addEdge(4, 0)
    g.addEdge(4, 1)
    g.addEdge(2, 3)
    g.addEdge(3, 1)
 
    print("Following is a Topological Sort of the given graph")
 
    # Function Call
    g.topologicalSort()
 
# This code is contributed by Neelam Yadav

Time complexity: linear
Space complexity: linear
# Python program to print topological sorting of a DAG
from collections import defaultdict
 
# Class to represent a graph
 
 
class Graph:
    def __init__(self, vertices):
        self.graph = defaultdict(list)  # dictionary containing adjacency List
        self.V = vertices  # No. of vertices
 
    # function to add an edge to graph
    def addEdge(self, u, v):
        self.graph[u].append(v)
 
    # neighbors generator given key
    def neighbor_gen(self, v):
        for k in self.graph[v]:
            yield k
 
    # non recursive topological sort
    def nonRecursiveTopologicalSortUtil(self, v, visited, stack):
 
        # working stack contains key and the corresponding current generator
        working_stack = [(v, self.neighbor_gen(v))]
 
        while working_stack:
            # get last element from stack
            v, gen = working_stack.pop()
            visited[v] = True
 
            # run through neighbor generator until it's empty
            for next_neighbor in gen:
                if not visited[next_neighbor]:  # not seen before?
                    # remember current work
                    working_stack.append((v, gen))
                    # restart with new neighbor
                    working_stack.append(
                        (next_neighbor, self.neighbor_gen(next_neighbor)))
                    break
            else:
                # no already-visited neighbor (or no more of them)
                stack.append(v)
 
    # The function to do Topological Sort.
    def nonRecursiveTopologicalSort(self):
        # Mark all the vertices as not visited
        visited = [False]*self.V
 
        # result stack
        stack = []
 
        # Call the helper function to store Topological
        # Sort starting from all vertices one by one
        for i in range(self.V):
            if not(visited[i]):
                self.nonRecursiveTopologicalSortUtil(i, visited, stack)
        # Print contents of the stack in reverse
        stack.reverse()
        print(stack)
 
 
# Driver code
if __name__ == "__main__":
  g = Graph(6)
  g.addEdge(5, 2)
  g.addEdge(5, 0)
  g.addEdge(4, 0)
  g.addEdge(4, 1)
  g.addEdge(2, 3)
  g.addEdge(3, 1)
 
 
  # Function call
  print("The following is a Topological Sort of the given graph")
  g.nonRecursiveTopologicalSort()
# This code was based of Neelam Yadav's code, modified by Suhail Alnahari, Python-ified by Matthias Urlichhs

Time complexity: linear
Space complexity: linear
# class to represent a graph object
class Graph:
 
    # Constructor
    def __init__(self, edges, N):
 
        # A List of Lists to represent an adjacency list
        self.adjList = [[] for _ in range(N)]
 
        # stores in-degree of a vertex
        # initialize in-degree of each vertex by 0
        self.indegree = [0] * N
 
        # add edges to the undirected graph
        for (src, dest) in edges:
 
            # add an edge from source to destination
            self.adjList[src].append(dest)
 
            # increment in-degree of destination vertex by 1
            self.indegree[dest] = self.indegree[dest] + 1
 
 
# Recursive function to find
# all topological orderings of a given DAG
def findAllTopologicalOrders(graph, path, discovered, N):
 
    # do for every vertex
    for v in range(N):
 
        # proceed only if in-degree of current node is 0 and
        # current node is not processed yet
        if graph.indegree[v] == 0 and not discovered[v]:
 
            # for every adjacent vertex u of v,
            # reduce in-degree of u by 1
            for u in graph.adjList[v]:
                graph.indegree[u] = graph.indegree[u] - 1
 
            # include current node in the path
            # and mark it as discovered
            path.append(v)
            discovered[v] = True
 
            # recur
            findAllTopologicalOrders(graph, path, discovered, N)
 
            # backtrack: reset in-degree
            # information for the current node
            for u in graph.adjList[v]:
                graph.indegree[u] = graph.indegree[u] + 1
 
            # backtrack: remove current node from the path and
            # mark it as undiscovered
            path.pop()
            discovered[v] = False
 
    # print the topological order if
    # all vertices are included in the path
    if len(path) == N:
        print(path)
 
 
# Print all topological orderings of a given DAG
def printAllTopologicalOrders(graph):
 
    # get number of nodes in the graph
    N = len(graph.adjList)
 
    # create an auxiliary space to keep track of whether vertex is discovered
    discovered = [False] * N
 
    # list to store the topological order
    path = []
 
    # find all topological ordering and print them
    findAllTopologicalOrders(graph, path, discovered, N)
 
# Driver code
if __name__ == '__main__':
 
    # List of graph edges as per above diagram
    edges = [(5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1)]
 
    print("All Topological sorts")
 
    # Number of nodes in the graph
    N = 6
 
    # create a graph from edges
    graph = Graph(edges, N)
 
    # print all topological ordering of the graph
    printAllTopologicalOrders(graph)
 
# This code is contributed by Priyadarshini Kumari

Time complexity: quadratic
Space complexity: linear
# A Python program to print topological sorting of a graph
# using indegrees
from collections import defaultdict
 
# Class to represent a graph
class Graph:
    def __init__(self, vertices):
        self.graph = defaultdict(list) # dictionary containing adjacency List
        self.V = vertices # No. of vertices
 
    # function to add an edge to graph
    def addEdge(self, u, v):
        self.graph[u].append(v)
 
 
    # The function to do Topological Sort.
    def topologicalSort(self):
         
        # Create a vector to store indegrees of all
        # vertices. Initialize all indegrees as 0.
        in_degree = [0]*(self.V)
         
        # Traverse adjacency lists to fill indegrees of
           # vertices.  This step takes O(V + E) time
        for i in self.graph:
            for j in self.graph[i]:
                in_degree[j] += 1
 
        # Create an queue and enqueue all vertices with
        # indegree 0
        queue = []
        for i in range(self.V):
            if in_degree[i] == 0:
                queue.append(i)
 
        # Initialize count of visited vertices
        cnt = 0
 
        # Create a vector to store result (A topological
        # ordering of the vertices)
        top_order = []
 
        # One by one dequeue vertices from queue and enqueue
        # adjacents if indegree of adjacent becomes 0
        while queue:
 
            # Extract front of queue (or perform dequeue)
            # and add it to topological order
            u = queue.pop(0)
            top_order.append(u)
 
            # Iterate through all neighbouring nodes
            # of dequeued node u and decrease their in-degree
            # by 1
            for i in self.graph[u]:
                in_degree[i] -= 1
                # If in-degree becomes zero, add it to queue
                if in_degree[i] == 0:
                    queue.append(i)
 
            cnt += 1
 
        # Check if there was a cycle
        if cnt != self.V:
            print ("There exists a cycle in the graph")
        else :
            # Print topological order
            print (top_order)
 
 
g = Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
 
print ("Following is a Topological Sort of the given graph")
g.topologicalSort()
 
# This code is contributed by Neelam Yadav

Time complexity: linear
Space complexity: linear
# A Python3 program for Prim's Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency matrix representation of the graph
 
import sys  # Library for INT_MAX
 
 
class Graph():
 
    def __init__(self, vertices):
        self.V = vertices
        self.graph = [[0 for column in range(vertices)]
                      for row in range(vertices)]
 
    # A utility function to print the constructed MST stored in parent[]
    def printMST(self, parent):
        print("Edge \tWeight")
        for i in range(1, self.V):
            print(parent[i], "-", i, "\t", self.graph[i][parent[i]])
 
    # A utility function to find the vertex with
    # minimum distance value, from the set of vertices
    # not yet included in shortest path tree
    def minKey(self, key, mstSet):
 
        # Initialize min value
        min = sys.maxsize
 
        for v in range(self.V):
            if key[v] < min and mstSet[v] == False:
                min = key[v]
                min_index = v
 
        return min_index
 
    # Function to construct and print MST for a graph
    # represented using adjacency matrix representation
    def primMST(self):
 
        # Key values used to pick minimum weight edge in cut
        key = [sys.maxsize] * self.V
        parent = [None] * self.V  # Array to store constructed MST
        # Make key 0 so that this vertex is picked as first vertex
        key[0] = 0
        mstSet = [False] * self.V
 
        parent[0] = -1  # First node is always the root of
 
        for cout in range(self.V):
 
            # Pick the minimum distance vertex from
            # the set of vertices not yet processed.
            # u is always equal to src in first iteration
            u = self.minKey(key, mstSet)
 
            # Put the minimum distance vertex in
            # the shortest path tree
            mstSet[u] = True
 
            # Update dist value of the adjacent vertices
            # of the picked vertex only if the current
            # distance is greater than new distance and
            # the vertex in not in the shortest path tree
            for v in range(self.V):
 
                # graph[u][v] is non zero only for adjacent vertices of m
                # mstSet[v] is false for vertices not yet included in MST
                # Update the key only if graph[u][v] is smaller than key[v]
                if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
                    key[v] = self.graph[u][v]
                    parent[v] = u
 
        self.printMST(parent)
 
 
# Driver's code
if __name__ == '__main__':
    g = Graph(5)
    g.graph = [[0, 2, 0, 6, 0],
               [2, 0, 3, 8, 5],
               [0, 3, 0, 0, 7],
               [6, 8, 0, 0, 9],
               [0, 5, 7, 9, 0]]
 
    g.primMST()
 
    # Contributed by Divyanshu Mehta

Time complexity: quadratic
Space complexity: linear