Banana-Leopard/TASTY huggingface dataset:
// C++ Code implementation for above problem
#include <bits/stdc++.h>
using namespace std;
 
#define N 4
#define M 4
 
// QItem for current location and distance
// from source location
class QItem {
public:
    int row;
    int col;
    int dist;
    QItem(int x, int y, int w)
        : row(x), col(y), dist(w)
    {
    }
};
 
int minDistance(char grid[N][M])
{
    QItem source(0, 0, 0);
 
    // To keep track of visited QItems. Marking
    // blocked cells as visited.
    bool visited[N][M];
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++)
        {
            if (grid[i][j] == '0')
                visited[i][j] = true;
            else
                visited[i][j] = false;
 
            // Finding source
            if (grid[i][j] == 's')
            {
               source.row = i;
               source.col = j;
            }
        }
    }
 
    // applying BFS on matrix cells starting from source
    queue<QItem> q;
    q.push(source);
    visited[source.row][source.col] = true;
    while (!q.empty()) {
        QItem p = q.front();
        q.pop();
 
        // Destination found;
        if (grid[p.row][p.col] == 'd')
            return p.dist;
 
        // moving up
        if (p.row - 1 >= 0 &&
            visited[p.row - 1][p.col] == false) {
            q.push(QItem(p.row - 1, p.col, p.dist + 1));
            visited[p.row - 1][p.col] = true;
        }
 
        // moving down
        if (p.row + 1 < N &&
            visited[p.row + 1][p.col] == false) {
            q.push(QItem(p.row + 1, p.col, p.dist + 1));
            visited[p.row + 1][p.col] = true;
        }
 
        // moving left
        if (p.col - 1 >= 0 &&
            visited[p.row][p.col - 1] == false) {
            q.push(QItem(p.row, p.col - 1, p.dist + 1));
            visited[p.row][p.col - 1] = true;
        }
 
         // moving right
        if (p.col + 1 < M &&
            visited[p.row][p.col + 1] == false) {
            q.push(QItem(p.row, p.col + 1, p.dist + 1));
            visited[p.row][p.col + 1] = true;
        }
    }
    return -1;
}
 
// Driver code
int main()
{
    char grid[N][M] = { { '0', '*', '0', 's' },
                        { '*', '0', '*', '*' },
                        { '0', '*', '*', '*' },
                        { 'd', '*', '*', '*' } };
 
    cout << minDistance(grid);
    return 0;
}

Time complexity: quadratic
Space complexity: quadratic
// CPP program to compute number of sets
// in a binary matrix.
#include <bits/stdc++.h>
using namespace std;
 
const int m = 3; // no of columns
const int n = 2; // no of rows
 
// function to calculate the number of
// non empty sets of cell
long long countSets(int a[n][m])
{  
    // stores the final answer
    long long res = 0;
     
    // traverses row-wise
    for (int i = 0; i < n; i++)
    {
        int u = 0, v = 0;
        for (int j = 0; j < m; j++)
            a[i][j] ? u++ : v++;         
        res += pow(2,u)-1 + pow(2,v)-1;
    }
     
    // traverses column wise
    for (int i = 0; i < m; i++)
    {
        int u = 0, v = 0;
        for (int j = 0; j < n; j++)
             a[j][i] ? u++ : v++; 
        res += pow(2,u)-1 + pow(2,v)-1;
    }
     
    // at the end subtract n*m as no of
    // single sets have been added twice.
    return res-(n*m);
}
 
// driver program to test the above function.
int main() {
     
    int a[][3] = {(1, 0, 1),
                  (0, 1, 0)};
     
    cout << countSets(a);
     
    return 0;
}

Time complexity: quadratic
Space complexity: constant
// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <bits/stdc++.h>
 
using namespace std;
 
/* Searches the element x in mat[][]. If the
element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
int search(int mat[4][4], int n, int x)
{
    if (n == 0)
        return -1;
 
    // traverse through the matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            // if the element is found
            if (mat[i][j] == x) {
                cout << "Element found at (" << i << ", "
                     << j << ")\n";
                return 1;
            }
    }
 
    cout << "n Element not found";
    return 0;
}
 
// Driver code
int main()
{
    int mat[4][4] = { { 10, 20, 30, 40 },
                      { 15, 25, 35, 45 },
                      { 27, 29, 37, 48 },
                      { 32, 33, 39, 50 } };
 
    // Function call
    search(mat, 4, 29);
 
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Time complexity: quadratic
Space complexity: constant
// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <bits/stdc++.h>
using namespace std;
 
/* Searches the element x in mat[][]. If the
element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
int search(int mat[4][4], int n, int x)
{
    if (n == 0)
        return -1;
 
    int smallest = mat[0][0], largest = mat[n - 1][n - 1];
    if (x < smallest || x > largest)
        return -1;
 
    // set indexes for top right element
    int i = 0, j = n - 1;
    while (i < n && j >= 0) {
        if (mat[i][j] == x) {
            cout << "Element found at " << i << ", " << j;
            return 1;
        }
        if (mat[i][j] > x)
            j--;
 
        // Check if mat[i][j] < x
        else
            i++;
    }
 
    cout << "n Element not found";
    return 0;
}
 
// Driver code
int main()
{
    int mat[4][4] = { { 10, 20, 30, 40 },
                      { 15, 25, 35, 45 },
                      { 27, 29, 37, 48 },
                      { 32, 33, 39, 50 } };
 
    // Function call
    search(mat, 4, 29);
 
    return 0;
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)

Time complexity: linear
Space complexity: constant
#include <bits/stdc++.h>
using namespace std;
 
// Function to print alternating rectangles of 0 and X
void fill0X(int m, int n)
{
    /*  k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index
        i - iterator    */
    int i, k = 0, l = 0;
 
    // Store given number of rows and columns for later use
    int r = m, c = n;
 
    // A 2D array to store the output to be printed
    char a[m][n];
    char x = 'X'; // Initialize the character to be stored in a[][]
 
    // Fill characters in a[][] in spiral form. Every iteration fills
    // one rectangle of either Xs or Os
    while (k < m && l < n)
    {
        /* Fill the first row from the remaining rows */
        for (i = l; i < n; ++i)
            a[k][i] = x;
        k++;
 
        /* Fill the last column from the remaining columns */
        for (i = k; i < m; ++i)
            a[i][n-1] = x;
        n--;
 
        /* Fill the last row from the remaining rows */
        if (k < m)
        {
            for (i = n-1; i >= l; --i)
                a[m-1][i] = x;
            m--;
        }
 
        /* Print the first column from the remaining columns */
        if (l < n)
        {
            for (i = m-1; i >= k; --i)
                a[i][l] = x;
            l++;
        }
 
        // Flip character for next iteration
        x = (x == '0')? 'X': '0';
    }
 
    // Print the filled matrix
    for (i = 0; i < r; i++)
    {
        for (int j = 0; j < c; j++)
            cout <<" "<< a[i][j];
        cout <<"\n";
    }
}
 
/* Driver program to test above functions */
int main()
{
    puts("Output for m = 5, n = 6");
    fill0X(5, 6);
 
    puts("\nOutput for m = 4, n = 4");
    fill0X(4, 4);
 
    puts("\nOutput for m = 3, n = 4");
    fill0X(3, 4);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

Time complexity: quadratic
Space complexity: quadratic
// C++ program to print all elements
// of given matrix in diagonal order
#include <bits/stdc++.h>
using namespace std;
 
#define ROW 5
#define COL 4
 
// A utility function to find min
// of two integers
int minu(int a, int b)
{
    return (a < b) ? a : b;
}
 
// A utility function to find min
// of three integers
int min(int a, int b, int c)
{
    return minu(minu(a, b), c);
}
 
// A utility function to find
// max of two integers
int max(int a, int b)
{
    return (a > b) ? a : b;
}
 
// The main function that prints given
// matrix in diagonal order
void diagonalOrder(int matrix[][COL])
{
     
    // There will be ROW+COL-1 lines
    // in the output
    for(int line = 1;
            line <= (ROW + COL - 1);
            line++)
    {
         
        /* Get column index of the first element
           in this line of output.
           The index is 0 for first ROW lines and
           line - ROW for remaining lines  */
        int start_col =  max(0, line - ROW);
 
        /* Get count of elements in this line. The
           count of elements is equal to minimum of
           line number, COL-start_col and ROW */
         int count = min(line, (COL - start_col), ROW);
 
        /* Print elements of this line */
        for(int j = 0; j < count; j++)
            cout << setw(5) <<
            matrix[minu(ROW, line) - j - 1][start_col + j];
 
        /* Print elements of next
           diagonal on next line */
        cout << "\n";
    }
}
 
// Utility function to print a matrix
void printMatrix(int matrix[ROW][COL])
{
    for(int i = 0; i < ROW; i++)
    {
        for(int j = 0; j < COL; j++)
            cout << setw(5) << matrix[i][j];
             
        cout << "\n";
    }
}
 
// Driver code
int main()
{
    int M[ROW][COL] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 },
                        { 17, 18, 19, 20 },};
    cout << "Given matrix is " << endl;
    printMatrix(M);
 
    cout << "\nDiagonal printing of matrix is " << endl;
    diagonalOrder(M);
    return 0;
}
 
// This code is contributed by shubhamsingh10

Time complexity: quadratic
Space complexity: constant
#include <bits/stdc++.h>
#define R 5
#define C 4
using namespace std;
 
bool isValid(int i, int j)
{
    if (i < 0 || i >= R
        || j >= C || j < 0)
        return false;
    return true;
}
 
void diagonalOrder(int arr[][C])
{
    /* through this for loop we choose
       each element of first column as
       starting point and print diagonal
       starting at it.
    arr[0][0], arr[1][0]....arr[R-1][0]
    are all starting points */
    for (int k = 0; k < R; k++)
    {
        cout << arr[k][0] << " ";
       
        // set row index for next point in
        // diagonal
        int i = k - 1;
        
        // set column index for next point in
        //    diagonal
        int j = 1;
 
        /* Print Diagonally upward */
        while (isValid(i, j)) {
            cout << arr[i][j] << " ";
            i--;
           
            // move in upright direction
            j++;
        }
        cout << endl;
    }
 
    /* through this for loop we choose
       each element of last row as starting
       point (except the [0][c-1] it has
       already been processed in previous
       for loop) and print diagonal starting
       at it. arr[R-1][0], arr[R-1][1]....arr[R-1][c-1]
       are all starting points
     */
 
    // Note : we start from k = 1 to C-1;
    for (int k = 1; k < C; k++)
    {
        cout << arr[R - 1][k] << " ";
       
        // set row index for next point in
        // diagonal
        int i = R - 2;
         
        // set column index for next point in
        // diagonal
        int j = k + 1;
 
        /* Print Diagonally upward */
        while (isValid(i, j))
        {
            cout << arr[i][j] << " ";
            i--;
           
            // move in upright direction
            j++;
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
 
    int arr[][C] = {
        { 1, 2, 3, 4 },    
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 }, 
        { 13, 14, 15, 16 },
        { 17, 18, 19, 20 },
    };
    diagonalOrder(arr);
    return 0;
}

Time complexity: quadratic
Space complexity: constant
#include <bits/stdc++.h>
#define R 5
#define C 4
using namespace std;
 
void diagonalOrder(int arr[][C],
                   int n, int m)
{
    // we will use a 2D vector to
    // store the diagonals of our array
    // the 2D vector will have (n+m-1)
    // rows that is equal to the number of
    // diagonals
    vector<vector<int> > ans(n + m - 1);
 
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            ans[i + j].push_back(arr[j][i]);
        }
    }
 
    for (int i = 0; i < ans.size(); i++)
    {
        for (int j = 0; j < ans[i].size(); j++)
            cout << ans[i][j] << " ";
 
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    // we have a matrix of n rows
    // and m columns
    int n = 5, m = 4;
    int arr[][C] = {
        { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 },
        { 13, 14, 15, 16 },
        { 17, 18, 19, 20 },
    };
    
    // Function call
    diagonalOrder(arr, n, m);
    return 0;
}

Time complexity: quadratic
Space complexity: linear
// C++ implementation to find the total energy
// required to rearrange the numbers
#include <bits/stdc++.h>
 
using namespace std;
 
#define SIZE 100
 
// function to find the total energy
// required to rearrange the numbers
int calculateEnergy(int mat[SIZE][SIZE], int n)
{
    int i_des, j_des, q;
    int tot_energy = 0;
 
    // nested loops to access the elements
    // of the given matrix
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            // store quotient
            q = mat[i][j] / n;
 
            // final destination location (i_des, j_des) of
            // the element mat[i][j] is being calculated
            i_des = q;
            j_des = mat[i][j] - (n * q);
 
            // energy required for the movement of the
            // element mat[i][j] is calculated and then
            // accumulated in the 'tot_energy'
            tot_energy += abs(i_des - i) + abs(j_des - j);
        }
    }
 
    // required total energy
    return tot_energy;
}
 
// Driver program to test above
int main()
{
    int mat[SIZE][SIZE] = { { 4, 7, 0, 3 },
                            { 8, 5, 6, 1 },
                            { 9, 11, 10, 2 },
                            { 15, 13, 14, 12 } };
    int n = 4;
 
    cout << "Total energy required = "
         << calculateEnergy(mat, n) << " units";
 
    return 0;
}

Time complexity: quadratic
Space complexity: constant
// C++ program to count unique cells in
// a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
 
// Returns true if mat[i][j] is unique
bool isUnique(int mat[][MAX], int i, int j,
                              int n, int m)
{
    // checking in row calculating sumrow
    // will be moving  column wise
    int sumrow = 0;
    for (int k = 0; k < m; k++) {
        sumrow += mat[i][k];
        if (sumrow > 1)
           return false;
    }
 
    // checking in column calculating sumcol
    // will be moving  row wise
    int sumcol = 0;
    for (int k = 0; k < n; k++) {
        sumcol += mat[k][j];
        if (sumcol > 1)
            return false;
    }
 
    return true;
}
 
int countUnique(int mat[][MAX], int n, int m)
{
    int uniquecount = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (mat[i][j] &&
             isUnique(mat, i, j, n, m))
                    uniquecount++;
    return uniquecount;
}
 
// Driver code
int main()
{
    int mat[][MAX] = {{0, 1, 0, 0},
                   {0, 0, 1, 0},
                   {1, 0, 0, 1}};
    cout << countUnique(mat, 3, 4);
    return 0;
}

Time complexity: quadratic
Space complexity: constant
// Efficient C++ program to count unique
// cells in a binary matrix
#include <bits/stdc++.h>
using namespace std;
 
const int MAX = 100;
 
int countUnique(int mat[][MAX], int n, int m)
{
    int rowsum[n], colsum[m];
    memset(colsum, 0, sizeof(colsum));
    memset(rowsum, 0, sizeof(rowsum));
 
    // Count number of 1s in each row
    // and in each column
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (mat[i][j])
            {
                rowsum[i]++;
                colsum[j]++;
            }
 
    // Using above count arrays, find
    // cells
    int uniquecount = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (mat[i][j] &&
                rowsum[i] == 1 &&
                colsum[j] == 1)
                    uniquecount++;
    return uniquecount;
}
 
// Driver code
int main()
{
    int mat[][MAX] = {{0, 1, 0, 0},
                {0, 0, 1, 0},
                {1, 0, 0, 1}};
    cout << countUnique(mat, 3, 4);
    return 0;
}

Time complexity: quadratic
Space complexity: linear
// CPP program for counting number of cell
// equals to given x
#include<bits/stdc++.h>
using namespace std;
 
// function to count factors as number of cell
int count (int n, int x)
{
    int count=0;
    // traverse and find the factors
    for (int i=1; i<=n && i<=x ; i++)
    {
        // x%i == 0 means i is factor of x
        // x/i <= n means i and j are <= n (for i*j=x)
        if ( x/i <= n && x%i ==0)
            count++;
    }
    // return count
    return count;
}
 
// driver program
int main()
{
    int n = 8;
    // we can manually assume matrix of order 8*8
    // where mat[i][j] = i*j , 0<i,j<=n
    int x =  24;
    cout << count(n, x);
    return 0;
}

Time complexity: linear
Space complexity: constant
// CPP code to check if a matrix is
// sparse.
#include <iostream>
using namespace std;
 
const int MAX = 100;
 
bool isSparse(int array[][MAX], int m, int n)
{
    int counter = 0;
 
    // Count number of zeros in the matrix
    for (int i = 0; i < m; ++i)
        for (int j = 0; j < n; ++j)
            if (array[i][j] == 0)
                ++counter;
 
    return (counter > ((m * n) / 2));
}
 
// Driver Function
int main()
{
    int array[][MAX] = { { 1, 0, 3 },
                        { 0, 0, 4 },
                        { 6, 0, 0 } };
 
    int m = 3,
        n = 3;
    if (isSparse(array, m, n))
        cout << "Yes";
    else
        cout << "No";
}

Time complexity: quadratic
Space complexity: constant
// CPP program to find common elements in
// two diagonals.
#include <iostream>
#define MAX 100
using namespace std;
 
// Returns count of row wise same
// elements in two diagonals of
// mat[n][n]
int countCommon(int mat[][MAX], int n)
{
    int res = 0;
    for (int i=0;i<n;i++)
        if (mat[i][i] == mat[i][n-i-1])
             res++;
    return res;
}
 
// Driver Code
int main()
{
    int mat[][MAX] = {{1, 2, 3},
                      {4, 5, 6},
                      {7, 8, 9}};
    cout << countCommon(mat, 3);
    return 0;
}

Time complexity: linear
Space complexity: constant
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
 
// Function to check the if sum of a row
// is same as corresponding column
bool areSumSame(int a[][MAX], int n, int m)
{
    int sum1 = 0, sum2 = 0;
    for (int i = 0; i < min(n, m); i++) {
        sum1 = 0, sum2 = 0;
        for (int j = 0; j < min(n, m); j++) {
            sum1 += a[i][j];
            sum2 += a[j][i];
        }
        if (sum1 == sum2)
            return true;
    }
    return false;
}
 
// Driver Code
int main()
{
    int n = 4; // number of rows
    int m = 4; // number of columns
    int M[n][MAX] = { { 1, 2, 3, 4 },
                      { 9, 5, 3, 1 },
                      { 0, 3, 5, 6 },
                      { 0, 4, 5, 6 } };
    cout << areSumSame(M, n, m) << "\n";
    return 0;
}

Time complexity: linear
Space complexity: constant
// CPP program to find row with maximum 1
// in row sorted binary matrix
#include<bits/stdc++.h>
#define N 4
using namespace std;
 
// function for finding row with maximum 1
void findMax (int arr[][N])
{
    int row = 0, i, j;
    for (i=0, j=N-1; i<N;i++)
    {
        // find left most position of 1 in a row
        // find 1st zero in a row
        while (arr[i][j] == 1 && j >= 0)
        {
            row = i;
            j--;
        }
    }
    cout << "Row number = " << row+1;
    cout << ", MaxCount = " << N-1-j;
}
 
// driver program
int main()
{
    int arr[N][N] = {0, 0, 0, 1,
                     0, 0, 0, 1,
                     0, 0, 0, 0,
                     0, 1, 1, 1};
    findMax(arr);
    return 0;
}

Time complexity: linear
Space complexity: constant
// Simple c++ code for check a matrix is
// symmetric or not.
#include <iostream>
using namespace std;
 
const int MAX = 100;
 
// Fills transpose of mat[N][N] in tr[N][N]
void transpose(int mat[][MAX], int tr[][MAX], int N)
{
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            tr[i][j] = mat[j][i];
}
 
// Returns true if mat[N][N] is symmetric, else false
bool isSymmetric(int mat[][MAX], int N)
{
    int tr[N][MAX];
    transpose(mat, tr, N);
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            if (mat[i][j] != tr[i][j])
                return false;
    return true;
}
 
// Driver code
int main()
{
    int mat[][MAX] = { { 1, 3, 5 },
                       { 3, 2, 4 },
                       { 5, 4, 1 } };
 
    if (isSymmetric(mat, 3))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Time complexity: quadratic
Space complexity: quadratic
// Efficient c++ code for check a matrix is
// symmetric or not.
#include <iostream>
using namespace std;
 
const int MAX = 100;
 
// Returns true if mat[N][N] is symmetric, else false
bool isSymmetric(int mat[][MAX], int N)
{
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            if (mat[i][j] != mat[j][i])
                return false;
    return true;
}
 
// Driver code
int main()
{
    int mat[][MAX] = { { 1, 3, 5 },
                       { 3, 2, 4 },
                       { 5, 4, 1 } };
 
    if (isSymmetric(mat, 3))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Time complexity: quadratic
Space complexity: constant
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// function which tells all cells are visited or not
bool isAllCellTraversed(vector<vector<pair<int,int>>>grid, int n, int m)
{
    bool visited[n][m];
    int total = n*m;
   
    // starting cell values
    int startx = grid[0][0].first;
    int starty = grid[0][0].second;
 
    for (int i = 0; i < total - 2; i++)
    {
 
        // if we get {0,0} before the end of loop
        // then returns false. Because it means we
        // didn't traverse all the cells
        if (grid[startx][starty].first == -1 and
            grid[startx][starty].second == -1)
            return false;
 
        // If found cycle then return false
        if (visited[startx][starty] == true)
            return false;
 
        visited[startx][starty] = true;
        int x = grid[startx][starty].first;
        int y = grid[startx][starty].second;
 
        // Update startx and starty values to next
        // cell values
        startx = x;
        starty = y;
    }
 
    // finally if we reach our goal then returns true
    if (grid[startx][starty].first == -1 and
        grid[startx][starty].second == -1)
        return true;
 
    return false;
}
 
// Driver code
int main()
{
  vector<vector<pair<int,int>>> cell(3, vector<pair<int,int>> (2));
  cell[0][0] = {0, 1};
  cell[0][1] = {2, 0};
  cell[1][0] = {-1,-1};
  cell[1][1] = {1, 0};
  cell[2][0] = {2, 1};
  cell[2][1] = {1, 1};
 
  if(!isAllCellTraversed(cell, 3, 2))
    cout << "true";
  else
    cout << "false";
 
  return 0;
}
 
// This code is contributed by mohit kumar 29.

Time complexity: linear
Space complexity: quadratic