Banana-Leopard/TASTY huggingface dataset:
# Python program to print cells with same rectangular
# sum diagonally
# R 4
# C 4
  
# Method prints cell index at which rectangular sum is
# same at prime diagonal and other diagonal
def printCellWithSameRectangularArea(mat, m, n):
    # sum[i][j] denotes sum of sub-matrix, mat[0][0]
    #  to mat[i][j]
    # sumr[i][j] denotes sum of sub-matrix, mat[i][j]
    # to mat[m - 1][n - 1] 
    sum = [[0 for i in range(m)]for j in range(n)]
    sumr = [[0 for i in range(m)]for j in range(n)]
  
    #  Initialize both sum matrices by mat
    totalSum = 0
    for i in range(m):
        for j in range(n):
            sumr[i][j] = sum[i][j] = mat[i][j];
            totalSum += mat[i][j]
  
    #  updating first and last row separately
    for i in range(1,m):
        sum[i][0] += sum[i-1][0]
        sumr[m-i-1][n-1] += sumr[m-i][n-1]
  
    #  updating first and last column separately
    for j in range(1,n):
        sum[0][j] += sum[0][j-1];
        sumr[m-1][n-j-1] += sumr[m-1][n-j]
  
    #  updating sum and sumr indices by nearby indices
    for i in range(1,m):
        for j in range(1,n):
            sum[i][j] += sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1]
            sumr[m-i-1][n-j-1] += sumr[m-i][n-j-1] + sumr[m-i-1][n-j] - sumr[m-i][n-j]
  
    #  Uncomment below code to print sum and reverse sum
    # matrix
  
    # print all those indices at which sum of prime diagonal
    #   rectangles is half of the total sum of matrix 
    for i in range(m):
        for j in range(n):
            mainDiagRectangleSum = sum[i][j] + sumr[i][j] - mat[i][j]
            if (totalSum == 2 * mainDiagRectangleSum):
                print ("(",i,",",j,")")
  
#  Driver code to test above methods
mat =[[1, 2, 3, 5,],
     [4, 1, 0, 2,],
     [0, 1, 2, 0],
     [7, 1, 1, 0]]
printCellWithSameRectangularArea(mat, 4, 4)
 
# Contributed by Afzal

Time complexity: quadratic
Space complexity: quadratic
# Python 3 program to print matrix in diagonal order
MAX = 100
 
def printMatrixDiagonal(mat, n):
    # Initialize indexes of element to be printed next
    i = 0
    j = 0
    k = 0
    # Direction is initially from down to up
    isUp = True
 
     # Traverse the matrix till all elements get traversed
    while k<n * n:
         # If isUp = True then traverse from downward
         # to upward
        if isUp:
            while i >= 0 and j<n :
                print(str(mat[i][j]), end = " ")
                k += 1
                j += 1
                i -= 1
 
              # Set i and j according to direction
            if i < 0 and j <= n - 1:
                i = 0
            if j == n:
                i = i + 2
                j -= 1
 
         # If isUp = 0 then traverse up to down
        else:
            while j >= 0 and i<n :
                print(mat[i][j], end = " ")
                k += 1
                i += 1
                j -= 1
 
              # Set i and j according to direction
            if j < 0 and i <= n - 1:
                j = 0
            if i == n:
                j = j + 2
                i -= 1
 
         # Revert the isUp to change the direction
        isUp = not isUp
 
# Driver program
if __name__ == "__main__":
    mat = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9] ]
 
   n = 3
   printMatrixDiagonal(mat, n)
 
# This code is contributed by Chitra Nayal

Time complexity: quadratic
Space complexity: constant
# Python3 program to print matrix in diagonal order
 
# Driver code
 
# Initialize matrix
mat = [[ 1, 2, 3, 4 ],
       [ 5, 6, 7, 8 ],
       [ 9, 10, 11, 12 ],
       [ 13, 14, 15, 16 ]];
        
# n - size
# mode - switch to derive up/down traversal
# it - iterator count - increases until it
# reaches n and then decreases
n = 4
mode = 0
it = 0
lower = 0
 
# 2n will be the number of iterations
for t in range(2 * n - 1):
    t1 = t
    if (t1 >= n):
        mode += 1
        t1 = n - 1
        it -= 1
        lower += 1
    else:
        lower = 0
        it += 1
 
    for i in range(t1, lower - 1, -1):
        if ((t1 + mode) % 2 == 0):
            print((mat[i][t1 + lower - i]))
        else:
            print(mat[t1 + lower - i][i])
 
# This code is contributed by princiraj1992

Time complexity: quadratic
Space complexity: constant
# Python3 program to find maximum difference
# of sum of elements of two rows
 
# Function to find maximum difference of
# sum of elements of two rows such that
# second row appears before first row.
def maxRowDiff(mat, m, n):
     
    # auxiliary array to store sum of
    # all elements of each row
    rowSum = [0] * m
     
    # calculate sum of each row and
    # store it in rowSum array
    for i in range(0, m):
        sum = 0
        for j in range(0, n):
            sum += mat[i][j]
        rowSum[i] = sum
     
    # calculating maximum difference of
    # two elements such that
    # rowSum[i]<rowsum[j]
    max_diff = rowSum[1] - rowSum[0]
    min_element = rowSum[0]
     
    for i in range(1, m):
     
        # if current difference is greater
        # than previous then update it
        if (rowSum[i] - min_element > max_diff):
            max_diff = rowSum[i] - min_element
         
        # if new element is less than previous
        # minimum element then update it so
        # that we may get maximum difference
        # in remaining array
        if (rowSum[i] < min_element):
            min_element = rowSum[i]
    return max_diff
 
# Driver program to run the case
m = 5
n = 4
mat = [[-1, 2, 3, 4],
       [5, 3, -2, 1],
       [6, 7, 2, -3],
       [2, 9, 1, 4],
       [2, 1, -2, 0]]
 
print( maxRowDiff(mat, m, n))
 
# This code is contributed by Swetank Modi

Time complexity: quadratic
Space complexity: linear
# Python3 program to get total coverage of all zeros in
# a binary matrix
R = 4
C = 4
 
# Returns total coverage of all zeros in mat[][]
def getTotalCoverageOfMatrix(mat):
    res = 0
     
    # looping for all rows of matrix
    for i in range(R):
         
        isOne = False # 1 is not seen yet
         
        # looping in columns from left to right
        # direction to get left ones
        for j in range(C):
             
            # If one is found from left
            if (mat[i][j] == 1):
                isOne = True
                 
            # If 0 is found and we have found
            # a 1 before.
            else if (isOne):
                res += 1
             
        # Repeat the above process for right to
        # left direction.
        isOne = False
        for j in range(C - 1, -1, -1):
            if (mat[i][j] == 1):
                isOne = True
            else if (isOne):
                res += 1
     
    # Traversing across columns for up and down
    # directions.
    for j in range(C):
        isOne = False # 1 is not seen yet
        for i in range(R):
             
            if (mat[i][j] == 1):
                isOne = True
            else if (isOne):
                res += 1
         
        isOne = False
        for i in range(R - 1, -1, -1):
            if (mat[i][j] == 1):
                isOne = True
            else if (isOne):
                res += 1
                 
    return res
 
# Driver code
mat = [[0, 0, 0, 0],[1, 0, 0, 1],[0, 1, 1, 0],[0, 1, 0, 0]]
print(getTotalCoverageOfMatrix(mat))
 
# This code is contributed by shubhamsingh10

Time complexity: quadratic
Space complexity: constant
# Python3 program to find number
# of sorted rows
def sortedCount(mat, r, c):
     
    result = 0
     
    # Start from left side of matrix to
    # count increasing order rows
    for i in range(r):
         
        # Check if there is any pair ofs element
        # that are not in increasing order.
        j = 0
        for j in range(c - 1):
            if mat[i][j + 1] <= mat[i][j]:
                break
     
        # If the loop didn't break (All elements
        # of current row were in increasing order)
        if j == c - 2:
            result += 1
 
    # Start from right side of matrix to
    # count increasing order rows ( reference
    # to left these are in decreasing order )
    for i in range(0, r):
 
        # Check if there is any pair ofs element
        # that are not in decreasing order.
        j = 0
        for j in range(c - 1, 0, -1):
            if mat[i][j - 1] <= mat[i][j]:
                break
         
        # Note c > 1 condition is required to
        # make sure that a single column row
        # is not counted twice (Note that a
        # single column row is sorted both
        # in increasing and decreasing order)
        if c > 1 and j == 1:
            result += 1
     
    return result    
 
# Driver code
m, n = 4, 5
 
mat = [[1, 2, 3, 4, 5],
       [4, 3, 1, 2, 6],
       [8, 7, 6, 5, 4],
       [5, 7, 8, 9, 10]]
 
print(sortedCount(mat, m, n))
 
# This code is contributed by
# Mohit kumar 29 (IIIT gwalior)

Time complexity: quadratic
Space complexity: constant
# Python3 program to Find maximum
# XOR value in matrix either row / column wise
 
# maximum number of row and column
MAX = 1000
  
# Function return the maximum
# xor value that is either row
# or column wise
def maxXOR(mat, N):
 
    # For row xor and column xor
    max_xor = 0
  
    # Traverse matrix
    for i in range(N):
     
        r_xor = 0
        c_xor = 0
        for j in range(N):
         
            # xor row element
            r_xor = r_xor ^ mat[i][j]
  
            # for each column : j is act as row & i
            # act as column xor column element
            c_xor = c_xor ^ mat[j][i]
         
  
        # update maximum between r_xor , c_xor
        if (max_xor < max(r_xor, c_xor)):
            max_xor =  max(r_xor, c_xor)
  
    # return maximum xor value
    return max_xor
  
# Driver Code
N = 3
  
mat= [[1 , 5, 4],
      [3 , 7, 2 ],
      [5 , 9, 10]]
  
print("maximum XOR value : ",
              maxXOR(mat, N))
               
# This code is contributed by Anant Agarwal.

Time complexity: quadratic
Space complexity: constant
# Python3 program to find how many mirror can transfer
# light from bottom to right
 
# method returns number of mirror which can transfer
# light from bottom to right
def maximumMirrorInMatrix(mat, N):
 
    # To store first obstacles horizontally (from right)
    # and vertically (from bottom)
    horizontal = [-1 for i in range(N)]
    vertical = [-1 for i in range(N)];
 
    # looping matrix to mark column for obstacles
    for i in range(N):
        for j in range(N - 1, -1, -1):
             
            if (mat[i][j] == 'B'):
                continue;
 
            # mark rightmost column with obstacle
            horizontal[i] = j;
            break;
         
 
    # looping matrix to mark rows for obstacles
    for j in range(N):
         
        for i in range(N - 1, -1, -1):
         
            if (mat[i][j] == 'B'):
                continue;
 
            # mark leftmost row with obstacle
            vertical[j] = i;
            break;
     
    res = 0; # Initialize result
 
    # if there is not obstacle on right or below,
    # then mirror can be placed to transfer light
    for i in range(N):
        for j in range(N):
     
            ''' if i > vertical[j] then light can from bottom
               if j > horizontal[i] then light can go to right '''
            if (i > vertical[j] and j > horizontal[i]):
             
                ''' uncomment this code to print actual mirror
                   position also'''
                res+=1;
             
    return res;
 
 
#  Driver code to test above method
N = 5;
 
#  B - Blank     O - Obstacle
mat = ["BBOBB",
                 "BBBBO",
                 "BBBBB",
                 "BOOBO",
                 "BBBOB"
                ];
 
print(maximumMirrorInMatrix(mat, N));
 
# This code is contributed by rutvik_56.

Time complexity: quadratic
Space complexity: linear
# Python3 program to check whether given
# matrix is a Toeplitz matrix or not
N = 5
M = 4
 
# Function to check if all elements present in
# descending diagonal starting from position
# (i, j) in the matrix are all same or not
 
 
def checkDiagonal(mat, i, j):
    res = mat[i][j]
    i += 1
    j += 1
 
    while (i < N and j < M):
 
        # mismatch found
        if (mat[i][j] != res):
            return False
 
        i += 1
        j += 1
 
    # we only reach here when all elements
    # in given diagonal are same
    return True
 
# Function to check whether given
# matrix is a Toeplitz matrix or not
 
 
def isToeplitz(mat):
 
    # do for each element in first row
    for j in range(M):
 
        # check descending diagonal starting from
        # position (0, j) in the matrix
        if not(checkDiagonal(mat, 0, j)):
            return False
 
    # do for each element in first column
    for i in range(1, N):
 
        # check descending diagonal starting
        # from position (i, 0) in the matrix
        if not(checkDiagonal(mat, i, 0)):
            return False
 
    return True
 
 
# Driver Code
if __name__ == "__main__":
 
    mat = [[6, 7, 8, 9],
           [4, 6, 7, 8],
           [1, 4, 6, 7],
           [0, 1, 4, 6],
           [2, 0, 1, 4]]
 
    # Function call
    if(isToeplitz(mat)):
        print("Matrix is a Toeplitz")
    else:
        print("Matrix is not a Toeplitz")
 
# This code is contributed by Jasmine K Grewal

Time complexity: quadratic
Space complexity: constant
# Python3 program to check whether given matrix
# is a Toeplitz matrix or not
 
def isToeplitz(matrix):
     
    # row = number of rows
    # col = number of columns
    row = len(matrix)
    col = len(matrix[0])
     
    # dictionary to store key,value pairs
    map = {}
    for i in range(row):
        for j in range(col):
            key = i-j
             
            # if key value exists in the map,
            if (key in map):
                 
                # we check whether the current value stored
                # in this key matches to element at current
                # index or not. If not, return false
                if (map[key] != matrix[i][j]):
                    return False
             
            # else we put key,value pair in map
            else:
                map[key] = matrix[i][j]
    return True
 
# Driver Code
if __name__ == "__main__":
    matrix = [[12, 23, -32], [-20, 12, 23], [56, -20, 12], [38, 56, -20]]
     
    # Function call
    if (isToeplitz(matrix)):
        print("Yes")
    else:
        print("No")

Time complexity: quadratic
Space complexity: linear
# Python program to count number
# of 0s in the given row-wise
# and column-wise sorted
# binary matrix.
 
# Function to count number
# of 0s in the given
# row-wise and column-wise
# sorted binary matrix.
def countZeroes(mat):
     
    # start from bottom-left
    # corner of the matrix
    N = 5;
    row = N - 1;
    col = 0;
 
    # stores number of
    # zeroes in the matrix
    count = 0;
 
    while (col < N):
         
        # move up until
        # you find a 0
        while (mat[row][col]):
             
            # if zero is not found
            # in current column, we
            # are done
            if (row < 0):
                return count;
            row = row - 1;
 
        # add 0s present in
        # current column to result
        count = count + (row + 1);
 
        # move right to
        # next column
        col = col + 1;
 
    return count;
     
# Driver Code
mat = [[0, 0, 0, 0, 1],
       [0, 0, 0, 1, 1],
       [0, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1]];
 
print( countZeroes(mat));
 
# This code is contributed
# by chandan_jnu

Time complexity: linear
Space complexity: constant
# Python3 Program to return previous element
# in an expanding matrix.
 
# Returns left of str in an
# expanding matrix of a, b, c, and d.
def findLeft(str):
    n = len(str) - 1;
 
    # Start from rightmost position
    while (n > 0):
         
        # If the current character is ‘b’ or ‘d’,
        # change to ‘a’ or ‘c’ respectively and
        # break the loop
        if (str[n] == 'd'):
            str = str[0:n] + 'c' + str[n + 1:];
            break;
 
        if (str[n] == 'b'):
            str = str[0:n] + 'a' + str[n + 1:];
            break;
 
        # If the current character is ‘a’ or ‘c’,
        # change it to ‘b’ or ‘d’ respectively
        if (str[n] == 'a'):
            str = str[0:n] + 'b' + str[n + 1:];
        else if (str[n] == 'c'):
            str = str[0:n] + 'd' + str[n + 1:];
        n-=1;
 
    return str;
 
# Driver Code
if __name__ == '__main__':
    str = "aacbddc";
    print("Left of", str, "is", findLeft(str));
 
# This code is contributed by PrinciRaj1992

Time complexity: linear
Space complexity: constant
# Python3 program to print a n x n spiral matrix
# in clockwise direction using O(1) space
 
# Prints spiral matrix of size n x n
# containing numbers from 1 to n x n
def printSpiral(n) :
     
    for i in range(0, n) :
        for j in range(0, n) :
             
            # Finds minimum of four inputs
            x = min(min(i, j), min(n - 1 - i, n - 1 - j))
             
            # For upper right half
            if (i <= j) :
                print((n - 2 * x) * (n - 2 * x) -
                      (i - x)- (j - x), end = "\t")
 
            # For lower left half
            else :
                print(((n - 2 * x - 2) *
                       (n - 2 * x - 2) +
                       (i - x) + (j - x)), end = "\t")
        print()
         
# Driver code
n = 5
 
# print a n x n spiral matrix
# in O(1) space
printSpiral(n)
 
# This code is contributed by Nikita Tiwari.

Time complexity: quadratic
Space complexity: constant
# Python3 code to implement the approach
import sys
 
# User defined Pair class
class Pair:
    def __init__(self, x, y):
        self.first = x
        self.second = y
 
# Check if it is possible to go to (x, y) from the current
# position. The function returns false if the cell has
# value 0 or already visited
def isSafe(mat, visited, x, y):
    return (x >= 0 and x < len(mat) and y >= 0 and y < len(mat[0]) and mat[x][y] == 1 and (not visited[x][y]))
 
def findShortestPath(mat, visited, i, j, x, y, min_dist, dist):
    if (i == x and j == y):
        min_dist = min(dist, min_dist)
        return min_dist
 
    # set (i, j) cell as visited
    visited[i][j] = True
     
    # go to the bottom cell
    if (isSafe(mat, visited, i + 1, j)):
        min_dist = findShortestPath(
            mat, visited, i + 1, j, x, y, min_dist, dist + 1)
 
    # go to the right cell
    if (isSafe(mat, visited, i, j + 1)):
        min_dist = findShortestPath(
            mat, visited, i, j + 1, x, y, min_dist, dist + 1)
 
    # go to the top cell
    if (isSafe(mat, visited, i - 1, j)):
        min_dist = findShortestPath(
            mat, visited, i - 1, j, x, y, min_dist, dist + 1)
 
    # go to the left cell
    if (isSafe(mat, visited, i, j - 1)):
        min_dist = findShortestPath(
            mat, visited, i, j - 1, x, y, min_dist, dist + 1)
 
    # backtrack: remove (i, j) from the visited matrix
    visited[i][j] = False
    return min_dist
 
# Wrapper over findShortestPath() function
def findShortestPathLength(mat, src, dest):
    if (len(mat) == 0 or mat[src.first][src.second] == 0
            or mat[dest.first][dest.second] == 0):
        return -1
 
    row = len(mat)
    col = len(mat[0])
 
    # construct an `M × N` matrix to keep track of visited
    # cells
    visited = []
    for i in range(row):
        visited.append([None for _ in range(col)])
 
    dist = sys.maxsize
    dist = findShortestPath(mat, visited, src.first,
                            src.second, dest.first, dest.second, dist, 0)
 
    if (dist != sys.maxsize):
        return dist
    return -1
 
# Driver code
mat = [[1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
       [1, 0, 1, 0, 1, 1, 1, 0, 1, 1],
       [1, 1, 1, 0, 1, 1, 0, 1, 0, 1],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
       [1, 1, 1, 0, 1, 1, 1, 0, 1, 0],
       [1, 0, 1, 1, 1, 1, 0, 1, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
       [1, 1, 0, 0, 0, 0, 1, 0, 0, 1]
       ]
 
src = Pair(0, 0)
dest = Pair(3, 4)
dist = findShortestPathLength(mat, src, dest)
if (dist != -1):
    print("Shortest Path is", dist)
 
else:
    print("Shortest Path doesn't exist")
 
# This code is contributed by phasing17

Time complexity: np
Space complexity: quadratic
# Python program to find the shortest
# path between a given source cell
# to a destination cell.
 
from collections import deque
ROW = 9
COL = 10
 
# To store matrix cell coordinates
class Point:
    def __init__(self,x: int, y: int):
        self.x = x
        self.y = y
 
# A data structure for queue used in BFS
class queueNode:
    def __init__(self,pt: Point, dist: int):
        self.pt = pt  # The coordinates of the cell
        self.dist = dist  # Cell's distance from the source
 
# Check whether given cell(row,col)
# is a valid cell or not
def isValid(row: int, col: int):
    return (row >= 0) and (row < ROW) and
                   (col >= 0) and (col < COL)
 
# These arrays are used to get row and column
# numbers of 4 neighbours of a given cell
rowNum = [-1, 0, 0, 1]
colNum = [0, -1, 1, 0]
 
# Function to find the shortest path between
# a given source cell to a destination cell.
def BFS(mat, src: Point, dest: Point):
     
    # check source and destination cell
    # of the matrix have value 1
    if mat[src.x][src.y]!=1 or mat[dest.x][dest.y]!=1:
        return -1
     
    visited = [[False for i in range(COL)]
                       for j in range(ROW)]
     
    # Mark the source cell as visited
    visited[src.x][src.y] = True
     
    # Create a queue for BFS
    q = deque()
     
    # Distance of source cell is 0
    s = queueNode(src,0)
    q.append(s) #  Enqueue source cell
     
    # Do a BFS starting from source cell
    while q:
 
        curr = q.popleft() # Dequeue the front cell
         
        # If we have reached the destination cell,
        # we are done
        pt = curr.pt
        if pt.x == dest.x and pt.y == dest.y:
            return curr.dist
         
        # Otherwise enqueue its adjacent cells
        for i in range(4):
            row = pt.x + rowNum[i]
            col = pt.y + colNum[i]
             
            # if adjacent cell is valid, has path 
            # and not visited yet, enqueue it.
            if (isValid(row,col) and
               mat[row][col] == 1 and
                not visited[row][col]):
                visited[row][col] = True
                Adjcell = queueNode(Point(row,col),
                                    curr.dist+1)
                q.append(Adjcell)
     
    # Return -1 if destination cannot be reached
    return -1
 
# Driver code
def main():
    mat = [[ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ],
           [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ],
           [ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 ],
           [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ],
           [ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 ],
           [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ],
           [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 ],
           [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ],
           [ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 ]]
    source = Point(0,0)
    dest = Point(3,4)
     
    dist = BFS(mat,source,dest)
     
    if dist!=-1:
        print("Shortest Path is",dist)
    else:
        print("Shortest Path doesn't exist")
main()
 
# This code is contributed by stutipathak31jan

Time complexity: quadratic
Space complexity: quadratic