Banana-Leopard/TASTY huggingface dataset:
// C++ program to check whether given matrix
// is a Toeplitz matrix or not
#include <iostream>
using namespace std;
#define N 5
#define 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
bool checkDiagonal(int mat[N][M], int i, int j)
{
    int res = mat[i][j];
    while (++i < N && ++j < M)
    {
        // mismatch found
        if (mat[i][j] != res)
            return false;
    }
 
    // 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
bool isToeplitz(int mat[N][M])
{
    // do for each element in first row
    for (int i = 0; i < M; i++)
    {
        // check descending diagonal starting from
        // position (0, j) in the matrix
        if (!checkDiagonal(mat, 0, i))
            return false;
    }
 
    // do for each element in first column
    for (int i = 1; i < N; i++)
    {
        // check descending diagonal starting from
        // position (i, 0) in the matrix
        if (!checkDiagonal(mat, i, 0))
            return false;
    }
 
    // we only reach here when each descending
    // diagonal from left to right is same
    return true;
}
 
// Driver code
int main()
{
    int mat[N][M] = { { 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))
        cout << "Matrix is a Toeplitz ";
    else
        cout << "Matrix is not a Toeplitz ";
 
    return 0;
}

Time complexity: quadratic
Space complexity: constant
// C++ program to check whether given
// matrix is a Toeplitz matrix or not
#include <bits/stdc++.h>
using namespace std;
 
bool isToeplitz(vector<vector<int>> matrix)
{
     
    // row = number of rows
    // col = number of columns
    int row = matrix.size();
    int col = matrix[0].size();
     
    // HashMap to store key,value pairs
    map<int, int> Map;
     
    for(int i = 0; i < row; i++)
    {
        for(int j = 0; j < col; j++)
        {
            int key = i - j;
             
            // If key value exists in the hashmap,
            if (Map[key])
            {
                 
                // 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 hashmap
            else
            {
                Map[i - j] = matrix[i][j];
            }
        }
    }
    return true;
}
 
// Driver code
int main()
{
    vector<vector<int>> matrix = { { 12, 23, -32 },
                                   { -20, 12, 23 },
                                   { 56, -20, 12 },
                                   { 38, 56, -20 } };
        
    // Function call
    string result = (isToeplitz(matrix)) ? "Yes" : "No";
     
    cout << result;
     
    return 0;
}
 
// This code is contributed by divyesh072019

Time complexity: quadratic
Space complexity: linear
// C++ Program to return previous element in an expanding
// matrix.
#include <bits/stdc++.h>
using namespace std;
 
// Returns left of str in an expanding matrix of
// a, b, c, and d.
string findLeft(string str)
{
    int n = str.length();
 
    // Start from rightmost position
    while (n--)
    {
        // If the current character is ‘b’ or ‘d’,
        // change to ‘a’ or ‘c’ respectively and
        // break the loop
        if (str[n] == 'd')
        {
            str[n] = 'c';
            break;
        }
        if (str[n] == 'b')
        {
            str[n] = 'a';
            break;
        }
 
        // If the current character is ‘a’ or ‘c’,
        // change it to ‘b’ or ‘d’ respectively
        if (str[n] == 'a')
            str[n] = 'b';
        else if (str[n] == 'c')
            str[n] = 'd';
    }
 
    return str;
}
 
// driver program to test above method
int main()
{
    string str = "aacbddc";
    cout << "Left of " << str << " is "
         << findLeft(str);
   return 0;
}

Time complexity: linear
Space complexity: constant
// C++ program to print a n x n spiral matrix
// in clockwise direction using O(1) space
#include <bits/stdc++.h>
using namespace std;
 
// Prints spiral matrix of size n x n containing
// numbers from 1 to n x n
void printSpiral(int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            // x stores the layer in which (i, j)th
            // element lies
            int x;
 
            // Finds minimum of four inputs
            x = min(min(i, j), min(n-1-i, n-1-j));
 
            // For upper right half
            if (i <= j)
                printf("%d\t ", (n-2*x)*(n-2*x) - (i-x)
                    - (j-x));
 
            // for lower left half
            else
                printf("%d\t ", (n-2*x-2)*(n-2*x-2) + (i-x)
                    + (j-x));
        }
        printf("\n");
    }
}
 
// Driver code
int main()
{
    int n = 5;
 
    // print a n x n spiral matrix in O(1) space
    printSpiral(n);
 
    return 0;
}

Time complexity: quadratic
Space complexity: constant
#include <iostream>
#include <vector>
#include <climits>
#include <cstring>
using namespace std;
  
// 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
bool isSafe(vector<vector<int>> &mat, vector<vector<bool>> &visited, int x, int y)
{
    return (x >= 0 && x < mat.size() && y >= 0 && y < mat[0].size()) &&
            mat[x][y] == 1 && !visited[x][y];
}
  
  
void findShortestPath(vector<vector<int>> &mat, vector<vector<bool>> &visited,
                int i, int j, int x, int y, int &min_dist, int dist){
    if (i == x && j == y){
        min_dist = min(dist, min_dist);
        return;
    }
    // set (i, j) cell as visited
    visited[i][j] = true;
    // go to the bottom cell
    if (isSafe(mat, visited, i + 1, j)) {
        findShortestPath(mat, visited, i + 1, j, x, y, min_dist, dist + 1);
    }
    // go to the right cell
    if (isSafe(mat, visited, i, j + 1)) {
        findShortestPath(mat, visited, i, j + 1, x, y, min_dist, dist + 1);
    }
    // go to the top cell
    if (isSafe(mat, visited, i - 1, j)) {
        findShortestPath(mat, visited, i - 1, j, x, y, min_dist, dist + 1);
    }
    // go to the left cell
    if (isSafe(mat, visited, i, j - 1)) {
        findShortestPath(mat, visited, i, j - 1, x, y, min_dist, dist + 1);
    }
    // backtrack: remove (i, j) from the visited matrix
    visited[i][j] = false;
}
  
// Wrapper over findShortestPath() function
int findShortestPathLength(vector<vector<int>> &mat, pair<int, int> &src,
                    pair<int, int> &dest){
    if (mat.size() == 0 || mat[src.first][src.second] == 0 ||
            mat[dest.first][dest.second] == 0)
        return -1;
     
    int row = mat.size();
    int col = mat[0].size();
    // construct an `M × N` matrix to keep track of visited cells
    vector<vector<bool>> visited;
    visited.resize(row, vector<bool>(col));
  
    int dist = INT_MAX;
    findShortestPath(mat, visited, src.first, src.second, dest.first, dest.second,
            dist, 0);
  
    if (dist != INT_MAX)
        return dist;
    return -1;
}
  
int main()
{
    vector<vector<int>> 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 }};
  
    pair<int, int> src = make_pair(0, 0);
    pair<int, int> dest = make_pair(3, 4);
    int dist = findShortestPathLength(mat, src, dest);
    if (dist != -1)
        cout << "Shortest Path is " << dist;
     
    else
        cout << "Shortest Path doesn't exist";
   
    return 0;
}

Time complexity: np
Space complexity: quadratic
// C++ program for finding orientation of the pattern
// using KMP pattern searching algorithm
#include<bits/stdc++.h>
using namespace std;
#define N 5
 
// Used in KMP Search for preprocessing the pattern
void computeLPSArray(char *pat, int M, int *lps)
{
    // length of the previous longest prefix suffix
    int len = 0;
    int i = 1;
 
    lps[0] = 0; // lps[0] is always 0
 
    // the loop calculates lps[i] for i = 1 to M-1
    while (i < M)
    {
        if (pat[i] == pat[len])
        {
            len++;
            lps[i++] = len;
        }
        else // (pat[i] != pat[len])
        {
            if (len != 0)
            {
                // This is tricky. Consider the example
                // AAACAAAA and i = 7.
                len = lps[len - 1];
 
                // Also, note that we do not increment i here
            }
            else // if (len == 0)
            {
                lps[i++] = 0;
            }
        }
    }
}
 
int KMPSearch(char *pat, char *txt)
{
    int M = strlen(pat);
 
    // create lps[] that will hold the longest
    // prefix suffix values for pattern
    int *lps = (int *)malloc(sizeof(int)*M);
    int j = 0; // index for pat[]
 
    // Preprocess the pattern (calculate lps[] array)
    computeLPSArray(pat, M, lps);
 
    int i = 0; // index for txt[]
    while (i < N)
    {
        if (pat[j] == txt[i])
        {
            j++;
            i++;
        }
        if (j == M)
        {
            // return 1 is pattern is found
            return 1;
        }
         
        // mismatch after j matches
        else if (i < N && pat[j] != txt[i])
        {
            // Do not match lps[0..lps[j-1]] characters,
            // they will match anyway
            if (j != 0)
                j = lps[j - 1];
            else
                i = i + 1;
        }
    }
    free(lps); // to avoid memory leak
     
    // return 0 is pattern is not found
    return 0;
}
 
// Function to find orientation of pattern in the matrix
// It uses KMP pattern searching algorithm
void findOrientation(char mat[][N], char *pat)
{
    // allocate memory for string containing cols
    char *col = (char*) malloc(N);
 
    for (int i = 0; i < N; i++)
    {
        // search in row i
        if (KMPSearch(pat, mat[i]))
        {
            cout << "Horizontal" << endl;
            return;
        }
 
        // Construct an array to store i'th column
        for (int j = 0; j < N; j++)
            col[j] = *(mat[j] + i);
 
        // Search in column i
        if (KMPSearch(pat, col))
            cout << "Vertical" << endl;
    }
 
    // to avoid memory leak
    free(col);
}
 
// Driver Code
int main()
{
    char mat[N][N] = {{'a', 'b', 'c', 'd', 'e'},
                      {'f', 'g', 'h', 'i', 'j'},
                       {'k', 'l', 'm', 'n', 'o'},
                      {'p', 'q', 'r', 's', 't'},
                      {'u', 'v', 'w', 'x', 'y'}};
    char pat[] = "pqrs";
 
    findOrientation(mat, pat);
 
    return 0;
}
 
// This code is contributed by kumar65

Time complexity: quadratic
Space complexity: linear
// A Naive method to find maximum value of mat[d][e]
// - ma[a][b] such that d > a and e > b
#include <bits/stdc++.h>
using namespace std;
#define N 5
 
// The function returns maximum value A(d,e) - A(a,b)
// over all choices of indexes such that both d > a
// and e > b.
int findMaxValue(int mat[][N])
{
    // stores maximum value
    int maxValue = INT_MIN;
 
    // Consider all possible pairs mat[a][b] and
    // mat[d][e]
    for (int a = 0; a < N - 1; a++)
    for (int b = 0; b < N - 1; b++)
        for (int d = a + 1; d < N; d++)
        for (int e = b + 1; e < N; e++)
            if (maxValue < (mat[d][e] - mat[a][b]))
                maxValue = mat[d][e] - mat[a][b];
 
    return maxValue;
}
 
// Driver program to test above function
int main()
{
int mat[N][N] = {
                { 1, 2, -1, -4, -20 },
                { -8, -3, 4, 2, 1 },
                { 3, 8, 6, 1, 3 },
                { -4, -1, 1, 7, -6 },
                { 0, -4, 10, -5, 1 }
            };
    cout << "Maximum Value is "
        << findMaxValue(mat);
 
    return 0;
}

Time complexity: np
Space complexity: constant
// An efficient method to find maximum value of mat[d]
// - ma[a][b] such that c > a and d > b
#include <bits/stdc++.h>
using namespace std;
#define N 5
 
// The function returns maximum value A(c,d) - A(a,b)
// over all choices of indexes such that both c > a
// and d > b.
int findMaxValue(int mat[][N])
{
    //stores maximum value
    int maxValue = INT_MIN;
 
    // maxArr[i][j] stores max of elements in matrix
    // from (i, j) to (N-1, N-1)
    int maxArr[N][N];
 
    // last element of maxArr will be same's as of
    // the input matrix
    maxArr[N-1][N-1] = mat[N-1][N-1];
 
    // preprocess last row
    int maxv = mat[N-1][N-1];  // Initialize max
    for (int j = N - 2; j >= 0; j--)
    {
        if (mat[N-1][j] > maxv)
            maxv = mat[N - 1][j];
        maxArr[N-1][j] = maxv;
    }
 
    // preprocess last column
    maxv = mat[N - 1][N - 1];  // Initialize max
    for (int i = N - 2; i >= 0; i--)
    {
        if (mat[i][N - 1] > maxv)
            maxv = mat[i][N - 1];
        maxArr[i][N - 1] = maxv;
    }
 
    // preprocess rest of the matrix from bottom
    for (int i = N-2; i >= 0; i--)
    {
        for (int j = N-2; j >= 0; j--)
        {
            // Update maxValue
            if (maxArr[i+1][j+1] - mat[i][j] >
                                            maxValue)
                maxValue = maxArr[i + 1][j + 1] - mat[i][j];
 
            // set maxArr (i, j)
            maxArr[i][j] = max(mat[i][j],
                               max(maxArr[i][j + 1],
                                   maxArr[i + 1][j]) );
        }
    }
 
    return maxValue;
}
 
// Driver program to test above function
int main()
{
    int mat[N][N] = {
                      { 1, 2, -1, -4, -20 },
                      { -8, -3, 4, 2, 1 },
                      { 3, 8, 6, 1, 3 },
                      { -4, -1, 1, 7, -6 },
                      { 0, -4, 10, -5, 1 }
                    };
    cout << "Maximum Value is "
         << findMaxValue(mat);
 
    return 0;
}

Time complexity: quadratic
Space complexity: quadratic
// An efficient C++ program to find maximum sum sub-square
// matrix
#include <bits/stdc++.h>
using namespace std;
 
// Size of given matrix
#define N 5
 
// A O(n^2) function to the maximum sum sub-squares of size
// k x k in a given square matrix of size n x n
void printMaxSumSub(int mat[][N], int k)
{
    // k must be smaller than or equal to n
    if (k > N)
        return;
 
    // 1: PREPROCESSING
    // To store sums of all strips of size k x 1
    int stripSum[N][N];
 
    // Go column by column
    for (int j = 0; j < N; j++) {
        // Calculate sum of first k x 1 rectangle in this
        // column
        int sum = 0;
        for (int i = 0; i < k; i++)
            sum += mat[i][j];
        stripSum[0][j] = sum;
 
        // Calculate sum of remaining rectangles
        for (int i = 1; i < N - k + 1; i++) {
            sum += (mat[i + k - 1][j] - mat[i - 1][j]);
            stripSum[i][j] = sum;
        }
    }
 
    // max_sum stores maximum sum and its position in matrix
    int max_sum = INT_MIN, *pos = NULL;
 
    // 2: CALCULATE SUM of Sub-Squares using stripSum[][]
    for (int i = 0; i < N - k + 1; i++) {
        // Calculate and print sum of first subsquare in
        // this row
        int sum = 0;
        for (int j = 0; j < k; j++)
            sum += stripSum[i][j];
 
        // Update max_sum and position of result
        if (sum > max_sum) {
            max_sum = sum;
            pos = &(mat[i][0]);
        }
 
        // Calculate sum of remaining squares in current row
        // by removing the leftmost strip of previous
        // sub-square and adding a new strip
        for (int j = 1; j < N - k + 1; j++) {
            sum += (stripSum[i][j + k - 1]
                    - stripSum[i][j - 1]);
 
            // Update max_sum and position of result
            if (sum > max_sum) {
                max_sum = sum;
                pos = &(mat[i][j]);
            }
        }
    }
 
    // Print the result matrix
    for (int i = 0; i < k; i++) {
        for (int j = 0; j < k; j++)
            cout << *(pos + i * N + j) << " ";
        cout << endl;
    }
}
 
// Driver program to test above function
int main()
{
    int mat[N][N] = {
        { 1, 1, 1, 1, 1 }, { 2, 2, 2, 2, 2 },
        { 3, 8, 6, 7, 3 }, { 4, 4, 4, 4, 4 },
        { 5, 5, 5, 5, 5 },
    };
    int k = 3;
 
    cout << "Maximum sum 3 x 3 matrix is\n";
    printMaxSumSub(mat, k);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Time complexity: quadratic
Space complexity: quadratic
// C++ Code For A Boolean Matrix Question
#include <bits/stdc++.h>
 
using namespace std;
#define R 3
#define C 4
 
void modifyMatrix(bool mat[R][C])
{
    bool row[R];
    bool col[C];
 
    int i, j;
 
    /* Initialize all values of row[] as 0 */
    for (i = 0; i < R; i++)
        row[i] = 0;
 
    /* Initialize all values of col[] as 0 */
    for (i = 0; i < C; i++)
        col[i] = 0;
 
    // Store the rows and columns to be marked as
    // 1 in row[] and col[] arrays respectively
    for (i = 0; i < R; i++) {
        for (j = 0; j < C; j++) {
            if (mat[i][j] == 1) {
                row[i] = 1;
                col[j] = 1;
            }
        }
    }
 
    // Modify the input matrix mat[] using the
    // above constructed row[] and col[] arrays
    for (i = 0; i < R; i++)
        for (j = 0; j < C; j++)
            if (row[i] == 1 || col[j] == 1)
                mat[i][j] = 1;
}
 
/* A utility function to print a 2D matrix */
void printMatrix(bool mat[R][C])
{
    int i, j;
    for (i = 0; i < R; i++) {
        for (j = 0; j < C; j++)
            cout << mat[i][j];
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    bool mat[R][C] = { { 1, 0, 0, 1 },
                       { 0, 0, 1, 0 },
                       { 0, 0, 0, 0 } };
 
    cout << "Input Matrix \n";
    printMatrix(mat);
    modifyMatrix(mat);
    printf("Matrix after modification \n");
    printMatrix(mat);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Time complexity: quadratic
Space complexity: linear
#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 4
 
void modifyMatrix(int mat[R][C])
{
    // variables to check if there are any 1
    // in first row and column
    bool row_flag = false;
    bool col_flag = false;
 
    // updating the first row and col if 1
    // is encountered
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            if (i == 0 && mat[i][j] == 1)
                row_flag = true;
 
            if (j == 0 && mat[i][j] == 1)
                col_flag = true;
 
            if (mat[i][j] == 1) {
 
                mat[0][j] = 1;
                mat[i][0] = 1;
            }
        }
    }
 
    // Modify the input matrix mat[] using the
    // first row and first column of Matrix mat
    for (int i = 1; i < R; i++)
        for (int j = 1; j < C; j++)
            if (mat[0][j] == 1 || mat[i][0] == 1)
                mat[i][j] = 1;
 
    // modify first row if there was any 1
    if (row_flag == true)
        for (int i = 0; i < C; i++)
            mat[0][i] = 1;
 
    // modify first col if there was any 1
    if (col_flag == true)
        for (int i = 0; i < R; i++)
            mat[i][0] = 1;
}
 
/* A utility function to print a 2D matrix */
void printMatrix(int mat[R][C])
{
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++)
            cout << mat[i][j] << " ";
        cout << "\n";
    }
}
 
// Driver function to test the above function
int main()
{
 
    int mat[R][C] = { { 1, 0, 0, 1 },
                      { 0, 0, 1, 0 },
                      { 0, 0, 0, 0 } };
 
    cout << "Input Matrix :\n";
    printMatrix(mat);
    modifyMatrix(mat);
    cout << "Matrix After Modification :\n";
    printMatrix(mat);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Time complexity: quadratic
Space complexity: constant
// C++ program to find i such that all entries in i'th row are 0
// and all entries in i't column are 1
#include <iostream>
using namespace std;
#define n 5
 
int find(bool arr[n][n])
{
    // Start from top-most rightmost corner
    // (We could start from other corners also)
    int i=0, j=n-1;
 
    // Initialize result
    int res = -1;
 
    // Find the index (This loop runs at most 2n times, we either
    // increment row number or decrement column number)
    while (i<n && j>=0)
    {
        // If current element is 0, then this row may be a solution
        if (arr[i][j] == 0)
        {
            // Check for all elements in this row
            while (j >= 0 && (arr[i][j] == 0 || i == j))
                j--;
 
            // If all values are 0, then store this row as result
            if (j == -1)
            {
                res = i;
                break;
            }
 
            // We reach here if we found a 1 in current row, so this
            //  row cannot be a solution, increment row number
            else i++;
        }
        else // If current element is 1
        {
            // Check for all elements in this column
            while (i<n && (arr[i][j] == 1 || i == j))
                i++;
 
            // If all elements are 1
            if (i == n)
            {
                res = j;
                break;
            }
 
            // We reach here if we found a 0 in current column, so this
            // column cannot be a solution, increment column number
            else j--;
        }
    }
 
    // If we could not find result in above loop, then result doesn't exist
    if (res == -1)
       return res;
 
    // Check if above computed res is valid
    for (int i=0; i<n; i++)
       if (res != i && arr[i][res] != 1)
          return -1;
    for (int j=0; j<n; j++)
       if (res != j && arr[res][j] != 0)
          return -1;
 
    return res;
}
 
 
/* Driver program to test above functions */
int main()
{
    bool mat[n][n] = {{0, 0, 1, 1, 0},
                      {0, 0, 0, 1, 0},
                      {1, 1, 1, 1, 0},
                      {0, 0, 0, 0, 0},
                      {1, 1, 1, 1, 1}};
    cout << find(mat);
 
    return 0;
}

Time complexity: linear
Space complexity: constant