Banana-Leopard/TASTY huggingface dataset:
# Python3 program to solve N Queen 
# Problem using backtracking
global N
N = 4
  
def printSolution(board): 
    for i in range(N):
        for j in range(N):
            print(board[i][j], end = " ")
        print() 
  
# A utility function to check if a queen can
# be placed on board[row][col]. Note that this
# function is called when "col" queens are
# already placed in columns from 0 to col -1.
# So we need to check only left side for
# attacking queens
def isSafe(board, row, col):
  
    # Check this row on left side
    for i in range(col):
        if board[row][i] == 1:
            return False
  
    # Check upper diagonal on left side
    for i, j in zip(range(row, -1, -1), 
                    range(col, -1, -1)):
        if board[i][j] == 1:
            return False
  
    # Check lower diagonal on left side
    for i, j in zip(range(row, N, 1), 
                    range(col, -1, -1)):
        if board[i][j] == 1:
            return False
  
    return True
  
def solveNQUtil(board, col):
      
    # base case: If all queens are placed
    # then return true
    if col >= N:
        return True
  
    # Consider this column and try placing
    # this queen in all rows one by one
    for i in range(N):
  
        if isSafe(board, i, col):
              
            # Place this queen in board[i][col]
            board[i][col] = 1
  
            # recur to place rest of the queens
            if solveNQUtil(board, col + 1) == True:
                return True
  
            # If placing queen in board[i][col
            # doesn't lead to a solution, then
            # queen from board[i][col]
            board[i][col] = 0
  
    # if the queen can not be placed in any row in
    # this column col then return false
    return False
  
# This function solves the N Queen problem using
# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.
def solveNQ():
    board = [ [0, 0, 0, 0],
              [0, 0, 0, 0],
              [0, 0, 0, 0],
              [0, 0, 0, 0] ]
  
    if solveNQUtil(board, 0) == False:
        print ("Solution does not exist")
        return False
  
    printSolution(board)
    return True
  
# Driver Code
solveNQ()
  
# This code is contributed by Divyanshu Mehta

Time complexity: np
Space complexity: quadratic
""" Python3 program to solve N Queen Problem using 
backtracking """
N = 4
  
""" ld is an array where its indices indicate row-col+N-1 
(N-1) is for shifting the difference to store negative 
indices """
ld = [0] * 30
  
""" rd is an array where its indices indicate row+col 
and used to check whether a queen can be placed on 
right diagonal or not"""
rd = [0] * 30
  
"""column array where its indices indicates column and 
used to check whether a queen can be placed in that 
    row or not"""
cl = [0] * 30
  
""" A utility function to print solution """
def printSolution(board): 
    for i in range(N):
        for j in range(N):
            print(board[i][j], end = " ")
        print() 
  
""" A recursive utility function to solve N 
Queen problem """
def solveNQUtil(board, col): 
      
    """ base case: If all queens are placed
        then return True """
    if (col >= N):
        return True
          
    """ Consider this column and try placing
        this queen in all rows one by one """
    for i in range(N):
          
        """ Check if the queen can be placed on board[i][col] """
        """ A check if a queen can be placed on board[row][col].
        We just need to check ld[row-col+n-1] and rd[row+coln] 
        where ld and rd are for left and right diagonal respectively"""
        if ((ld[i - col + N - 1] != 1 and 
             rd[i + col] != 1) and cl[i] != 1):
                   
            """ Place this queen in board[i][col] """
            board[i][col] = 1
            ld[i - col + N - 1] = rd[i + col] = cl[i] = 1
              
            """ recur to place rest of the queens """
            if (solveNQUtil(board, col + 1)):
                return True
                  
            """ If placing queen in board[i][col] 
            doesn't lead to a solution, 
            then remove queen from board[i][col] """
            board[i][col] = 0 # BACKTRACK 
            ld[i - col + N - 1] = rd[i + col] = cl[i] = 0
              
            """ If the queen cannot be placed in
            any row in this column col then return False """
    return False
      
""" This function solves the N Queen problem using 
Backtracking. It mainly uses solveNQUtil() to 
solve the problem. It returns False if queens 
cannot be placed, otherwise, return True and 
prints placement of queens in the form of 1s. 
Please note that there may be more than one 
solutions, this function prints one of the 
feasible solutions."""
def solveNQ():
    board = [[0, 0, 0, 0], 
             [0, 0, 0, 0],
             [0, 0, 0, 0],
             [0, 0, 0, 0]]
    if (solveNQUtil(board, 0) == False):
        printf("Solution does not exist")
        return False
    printSolution(board)
    return True
      
# Driver Code
solveNQ() 
  
# This code is contributed by SHUBHAMSINGH10

Time complexity: np
Space complexity: linear
# Python3 program for the above approach
 
# Number of vertices in the graph
# define 4 4
 
# check if the colored
# graph is safe or not
 
 
def isSafe(graph, color):
 
    # check for every edge
    for i in range(4):
        for j in range(i + 1, 4):
            if (graph[i][j] and color[j] == color[i]):
                return False
    return True
 
# /* This function solves the m Coloring
# problem using recursion. It returns
# false if the m colours cannot be assigned,
# otherwise, return true and prints
# assignments of colours to all vertices.
# Please note that there may be more than
# one solutions, this function prints one
# of the feasible solutions.*/
 
 
def graphColoring(graph, m, i, color):
 
    # if current index reached end
    if (i == 4):
 
        # if coloring is safe
        if (isSafe(graph, color)):
 
            # Print the solution
            printSolution(color)
            return True
        return False
 
    # Assign each color from 1 to m
    for j in range(1, m + 1):
        color[i] = j
 
        # Recur of the rest vertices
        if (graphColoring(graph, m, i + 1, color)):
            return True
        color[i] = 0
    return False
 
# /* A utility function to print solution */
 
 
def printSolution(color):
    print("Solution Exists:" " Following are the assigned colors ")
    for i in range(4):
        print(color[i], end=" ")
 
 
# Driver code
if __name__ == '__main__':
 
    # /* Create following graph and
    # test whether it is 3 colorable
    # (3)---(2)
    # | / |
    # | / |
    # | / |
    # (0)---(1)
    # */
    graph = [
        [0, 1, 1, 1],
        [1, 0, 1, 0],
        [1, 1, 0, 1],
        [1, 0, 1, 0],
    ]
    m = 3  # Number of colors
 
    # Initialize all color values as 0.
    # This initialization is needed
    # correct functioning of isSafe()
    color = [0 for i in range(4)]
 
    # Function call
    if (not graphColoring(graph, m, 0, color)):
        print("Solution does not exist")
 
# This code is contributed by mohit kumar 29

Time complexity: quadratic
Space complexity: linear
# Python3 program for solution of M Coloring
# problem using backtracking
 
 
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 check
    # if the current color assignment
    # is safe for vertex v
    def isSafe(self, v, colour, c):
        for i in range(self.V):
            if self.graph[v][i] == 1 and colour[i] == c:
                return False
        return True
 
    # A recursive utility function to solve m
    # coloring  problem
    def graphColourUtil(self, m, colour, v):
        if v == self.V:
            return True
 
        for c in range(1, m + 1):
            if self.isSafe(v, colour, c) == True:
                colour[v] = c
                if self.graphColourUtil(m, colour, v + 1) == True:
                    return True
                colour[v] = 0
 
    def graphColouring(self, m):
        colour = [0] * self.V
        if self.graphColourUtil(m, colour, 0) == None:
            return False
 
        # Print the solution
        print("Solution exist and Following are the assigned colours:")
        for c in colour:
            print(c, end=' ')
        return True
 
 
# Driver Code
if __name__ == '__main__':
    g = Graph(4)
    g.graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]]
    m = 3
 
    # Function call
    g.graphColouring(m)
 
# This code is contributed by Divyanshu Mehta

Time complexity: quadratic
Space complexity: linear
# Python3 program for the above approach
 
from queue import Queue
 
 
class node:
 
    color = 1
    edges = set()
 
 
def canPaint(nodes, n, m):
 
    # Create a visited array of n
    # nodes, initialized to zero
    visited = [0 for _ in range(n+1)]
 
    # maxColors used till now are 1 as
    # all nodes are painted color 1
    maxColors = 1
 
    # Do a full BFS traversal from
    # all unvisited starting points
    for _ in range(1, n + 1):
        if visited[_]:
            continue
 
        # If the starting point is unvisited,
        # mark it visited and push it in queue
        visited[_] = 1
        q = Queue()
        q.put(_)
 
        # BFS Travel starts here
        while not q.empty():
            top = q.get()
 
            # Checking all adjacent nodes
            # to "top" edge in our queue
            for _ in nodes[top].edges:
 
                # IMPORTANT: If the color of the
                # adjacent node is same, increase it by 1
 
                if nodes[top].color == nodes[_].color:
                    nodes[_].color += 1
 
                # If number of colors used shoots m,
                # return 0
                maxColors = max(maxColors, max(
                    nodes[top].color, nodes[_].color))
 
                if maxColors > m:
                    print(maxColors)
                    return 0
 
                # If the adjacent node is not visited,
                # mark it visited and push it in queue
                if not visited[_]:
                    visited[_] = 1
                    q.put(_)
 
    return 1
 
 
# Driver code
if __name__ == "__main__":
 
    n = 4
    graph = [[0, 1, 1, 1],
             [1, 0, 1, 0],
             [1, 1, 0, 1],
             [1, 0, 1, 0]]
 
    # Number of colors
    m = 3
 
    # Create a vector of n+1
    # nodes of type "node"
    # The zeroth position is just
    # dummy (1 to n to be used)
    nodes = []
    for _ in range(n+1):
        nodes.append(node())
 
    # Add edges to each node as
    # per given input
    for _ in range(n):
        for __ in range(n):
            if graph[_][__]:
 
                # Connect the undirected graph
                nodes[_].edges.add(_)
                nodes[__].edges.add(__)
 
    # Function call
    print(canPaint(nodes, n, m))
 
# This code is contributed by harshitkap00r

Time complexity: linear
Space complexity: linear
# Python program for Dijkstra's single
# source shortest path algorithm. The program is
# for adjacency matrix representation of the graph
 
# Library for INT_MAX
import sys
 
 
class Graph():
 
    def __init__(self, vertices):
        self.V = vertices
        self.graph = [[0 for column in range(vertices)]
                      for row in range(vertices)]
 
    def printSolution(self, dist):
        print("Vertex \tDistance from Source")
        for node in range(self.V):
            print(node, "\t", dist[node])
 
    # A utility function to find the vertex with
    # minimum distance value, from the set of vertices
    # not yet included in shortest path tree
    def minDistance(self, dist, sptSet):
 
        # Initialize minimum distance for next node
        min = sys.maxsize
 
        # Search not nearest vertex not in the
        # shortest path tree
        for u in range(self.V):
            if dist[u] < min and sptSet[u] == False:
                min = dist[u]
                min_index = u
 
        return min_index
 
    # Function that implements Dijkstra's single source
    # shortest path algorithm for a graph represented
    # using adjacency matrix representation
    def dijkstra(self, src):
 
        dist = [sys.maxsize] * self.V
        dist[src] = 0
        sptSet = [False] * self.V
 
        for cout in range(self.V):
 
            # Pick the minimum distance vertex from
            # the set of vertices not yet processed.
            # x is always equal to src in first iteration
            x = self.minDistance(dist, sptSet)
 
            # Put the minimum distance vertex in the
            # shortest path tree
            sptSet[x] = 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 y in range(self.V):
                if self.graph[x][y] > 0 and sptSet[y] == False and \
                        dist[y] > dist[x] + self.graph[x][y]:
                    dist[y] = dist[x] + self.graph[x][y]
 
        self.printSolution(dist)
 
 
# Driver's code
if __name__ == "__main__":
    g = Graph(9)
    g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
               [4, 0, 8, 0, 0, 0, 0, 11, 0],
               [0, 8, 0, 7, 0, 4, 0, 0, 2],
               [0, 0, 7, 0, 9, 14, 0, 0, 0],
               [0, 0, 0, 9, 0, 10, 0, 0, 0],
               [0, 0, 4, 14, 10, 0, 2, 0, 0],
               [0, 0, 0, 0, 0, 2, 0, 1, 6],
               [8, 11, 0, 0, 0, 0, 1, 0, 7],
               [0, 0, 2, 0, 0, 0, 6, 7, 0]
               ]
 
    g.dijkstra(0)
 
# This code is contributed by Divyanshu Mehta and Updated by Pranav Singh Sambyal

Time complexity: quadratic
Space complexity: linear
# Python3 program for Bellman-Ford's single source
# shortest path algorithm.
 
# Class to represent a graph
 
class Graph:
 
    def __init__(self, vertices):
        self.V = vertices  # No. of vertices
        self.graph = []
 
    # function to add an edge to graph
    def addEdge(self, u, v, w):
        self.graph.append([u, v, w])
 
    # utility function used to print the solution
    def printArr(self, dist):
        print("Vertex Distance from Source")
        for i in range(self.V):
            print("{0}\t\t{1}".format(i, dist[i]))
 
    # The main function that finds shortest distances from src to
    # all other vertices using Bellman-Ford algorithm. The function
    # also detects negative weight cycle
    def BellmanFord(self, src):
 
        # Step 1: Initialize distances from src to all other vertices
        # as INFINITE
        dist = [float("Inf")] * self.V
        dist[src] = 0
 
        # Step 2: Relax all edges |V| - 1 times. A simple shortest
        # path from src to any other vertex can have at-most |V| - 1
        # edges
        for _ in range(self.V - 1):
            # Update dist value and parent index of the adjacent vertices of
            # the picked vertex. Consider only those vertices which are still in
            # queue
            for u, v, w in self.graph:
                if dist[u] != float("Inf") and dist[u] + w < dist[v]:
                    dist[v] = dist[u] + w
 
        # Step 3: check for negative-weight cycles. The above step
        # guarantees shortest distances if graph doesn't contain
        # negative weight cycle. If we get a shorter path, then there
        # is a cycle.
 
        for u, v, w in self.graph:
            if dist[u] != float("Inf") and dist[u] + w < dist[v]:
                print("Graph contains negative weight cycle")
                return
 
        # print all distance
        self.printArr(dist)
 
 
# Driver's code
if __name__ == '__main__':
    g = Graph(5)
    g.addEdge(0, 1, -1)
    g.addEdge(0, 2, 4)
    g.addEdge(1, 2, 3)
    g.addEdge(1, 3, 2)
    g.addEdge(1, 4, 2)
    g.addEdge(3, 2, 5)
    g.addEdge(3, 1, 1)
    g.addEdge(4, 3, -3)
 
    # function call
    g.BellmanFord(0)
 
# Initially, Contributed by Neelam Yadav
# Later On, Edited by Himanshu Garg

Time complexity: quadratic
Space complexity: linear
# Python3 Program for Floyd Warshall Algorithm
 
# Number of vertices in the graph
V = 4
 
# Define infinity as the large
# enough value. This value will be
# used for vertices not connected to each other
INF = 99999
 
# Solves all pair shortest path
# via Floyd Warshall Algorithm
 
 
def floydWarshall(graph):
    """ dist[][] will be the output
       matrix that will finally
        have the shortest distances
        between every pair of vertices """
    """ initializing the solution matrix
    same as input graph matrix
    OR we can say that the initial
    values of shortest distances
    are based on shortest paths considering no
    intermediate vertices """
 
    dist = list(map(lambda i: list(map(lambda j: j, i)), graph))
 
    """ Add all vertices one by one
    to the set of intermediate
     vertices.
     ---> Before start of an iteration,
     we have shortest distances
     between all pairs of vertices
     such that the shortest
     distances consider only the
     vertices in the set
    {0, 1, 2, .. k-1} as intermediate vertices.
      ----> After the end of a
      iteration, vertex no. k is
     added to the set of intermediate
     vertices and the
    set becomes {0, 1, 2, .. k}
    """
    for k in range(V):
 
        # pick all vertices as source one by one
        for i in range(V):
 
            # Pick all vertices as destination for the
            # above picked source
            for j in range(V):
 
                # If vertex k is on the shortest path from
                # i to j, then update the value of dist[i][j]
                dist[i][j] = min(dist[i][j],
                                 dist[i][k] + dist[k][j]
                                 )
    printSolution(dist)
 
 
# A utility function to print the solution
def printSolution(dist):
    print("Following matrix shows the shortest distances\
 between every pair of vertices")
    for i in range(V):
        for j in range(V):
            if(dist[i][j] == INF):
                print("%7s" % ("INF"), end=" ")
            else:
                print("%7d\t" % (dist[i][j]), end=' ')
            if j == V-1:
                print()
 
 
# Driver's code
if __name__ == "__main__":
  """
              10
         (0)------->(3)
          |         /|\
        5 |          |
          |          | 1
         \|/         |
         (1)------->(2)
              3           """
  graph = [[0, 5, INF, 10],
         [INF, 0, 3, INF],
         [INF, INF, 0,   1],
         [INF, INF, INF, 0]
         ]
  # Function call
  floydWarshall(graph)
# This code is contributed by Mythri J L

Time complexity: cubic
Space complexity: quadratic
# Dynamic Programming based Python3
# program to find shortest path with
 
# A Dynamic programming based function
# to find the shortest path from u to v
# with exactly k edges.
def shortestPath(graph, u, v, k):
    global V, INF
     
    # Table to be filled up using DP. The
    # value sp[i][j][e] will store weight
    # of the shortest path from i to j
    # with exactly k edges
    sp = [[None] * V for i in range(V)]
    for i in range(V):
        for j in range(V):
            sp[i][j] = [None] * (k + 1)
 
    # Loop for number of edges from 0 to k
    for e in range(k + 1):
        for i in range(V): # for source
            for j in range(V): # for destination
             
                # initialize value
                sp[i][j][e] = INF
 
                # from base cases
                if (e == 0 and i == j):
                    sp[i][j][e] = 0
                if (e == 1 and graph[i][j] != INF):
                    sp[i][j][e] = graph[i][j]
 
                # go to adjacent only when number
                # of edges is more than 1
                if (e > 1):
                    for a in range(V):
                         
                        # There should be an edge from
                        # i to a and a should not be
                        # same as either i or j
                        if (graph[i][a] != INF and i != a and
                             j!= a and sp[a][j][e - 1] != INF):
                            sp[i][j][e] = min(sp[i][j][e], graph[i][a] +
                                              sp[a][j][e - 1])
                         
    return sp[u][v][k]
 
# Driver Code
 
# Define number of vertices in
# the graph and infinite value
V = 4
INF = 999999999999
 
# Let us create the graph shown
# in above diagram
graph = [[0, 10, 3, 2],
         [INF, 0, INF, 7],
         [INF, INF, 0, 6],
         [INF, INF, INF, 0]]
u = 0
v = 3
k = 2
print("Weight of the shortest path is",
          shortestPath(graph, u, v, k))
 
# This code is contributed by PranchalK

Time complexity: cubic
Space complexity: np
# Python program to get least cost path in a grid from
# top-left to bottom-right
from functools import cmp_to_key
 
ROW = 5
COL = 5
 
def mycmp(a,b):
     
    if (a.distance == b.distance):
        if (a.x != b.x):
            return (a.x - b.x)
        else:
            return (a.y - b.y)
    return (a.distance - b.distance)
 
# structure for information of each cell
class cell:
 
    def __init__(self,x, y, distance):
        self.x = x
        self.y = y
        self.distance = distance
 
# Utility method to check whether a point is
# inside the grid or not
def isInsideGrid(i, j):
    return (i >= 0 and i < ROW and j >= 0 and j < COL)
 
# Method returns minimum cost to reach bottom
# right from top left
def shortest(grid, row, col):
    dis = [[0 for i in range(col)]for j in range(row)]
 
    # initializing distance array by INT_MAX
    for i in range(row):
        for j in range(col):
            dis[i][j] = 1000000000
 
    # direction arrays for simplification of getting
    # neighbour
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
 
    st = []
 
    # insert (0, 0) cell with 0 distance
    st.append(cell(0, 0, 0))
 
    # initialize distance of (0, 0) with its grid value
    dis[0][0] = grid[0][0]
 
    # loop for standard dijkstra's algorithm
    while (len(st)!=0):
 
        # get the cell with minimum distance and delete
        # it from the set
        k = st[0]
        st = st[1:]
 
        # looping through all neighbours
        for i in range(4):
 
            x = k.x + dx[i]
            y = k.y + dy[i]
 
            # if not inside boundary, ignore them
            if (isInsideGrid(x, y) == 0):
                continue
 
            # If distance from current cell is smaller, then
            # update distance of neighbour cell
            if (dis[x][y] > dis[k.x][k.y] + grid[x][y]):
                # update the distance and insert new updated
                # cell in set
                dis[x][y] = dis[k.x][k.y] + grid[x][y]
                st.append(cell(x, y, dis[x][y]))
 
        st.sort(key=cmp_to_key(mycmp))
 
    # uncomment below code to print distance
    # of each cell from (0, 0)
 
    # for i in range(row):
    #     for j in range(col):
    #         print(dis[i][j] ,end= " ")
    #     print()
 
    # dis[row - 1][col - 1] will represent final
    # distance of bottom right cell from top left cell
    return dis[row - 1][col - 1]
 
# Driver code to test above methods
 
grid = [[31, 100, 65, 12, 18], [10, 13, 47, 157, 6], [100, 113, 174, 11, 33], [88, 124, 41, 20, 140],[99, 32, 111, 41, 20]]
print(shortest(grid, ROW, COL))
 
# This code is contributed by shinjanpatra

Time complexity: quadratic
Space complexity: quadratic