code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// C++ program to check if all rows of a matrix // are rotations of each other #include <bits/stdc++.h> using namespace std; const int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1] // are rotations of each other. bool isPermutedMatrix( int mat[MAX][MAX], int n) { // Creating a string that contains elements of first // row. string str_cat = ""; for (int i = 0 ; i < n ; i++) str_cat = str_cat + "-" + to_string(mat[0][i]); // Concatenating the string with itself so that // substring search operations can be performed on // this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i=1; i<n; i++) { // Store the matrix into vector in the form // of strings string curr_str = ""; for (int j = 0 ; j < n ; j++) curr_str = curr_str + "-" + to_string(mat[i][j]); // Check if the current string is present in // the concatenated string or not if (str_cat.find(curr_str) == string::npos) return false; } return true; } // Drivers code int main() { int n = 4 ; int mat[MAX][MAX] = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; isPermutedMatrix(mat, n)? cout << "Yes" : cout << "No"; return 0; }
linear
cubic
// C++ implementation to sort the given matrix #include <bits/stdc++.h> using namespace std; #define SIZE 10 // function to sort the given matrix void sortMat(int mat[SIZE][SIZE], int n) { // temporary matrix of size n^2 int temp[n * n]; int k = 0; // copy the elements of matrix one by one // into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] sort(temp, temp + k); // copy the elements of temp[] one by one // in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++]; } // function to print the given matrix void printMat(int mat[SIZE][SIZE], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; } } // Driver program to test above int main() { int mat[SIZE][SIZE] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; cout << "Original Matrix:\n"; printMat(mat, n); sortMat(mat, n); cout << "\nMatrix After Sorting:\n"; printMat(mat, n); return 0; }
quadratic
quadratic
// C++ program to find median of a matrix // sorted row wise #include<bits/stdc++.h> using namespace std; const int MAX = 100; // function to find median in the matrix int binaryMedian(int m[][MAX], int r ,int c) { int min = INT_MAX, max = INT_MIN; for (int i=0; i<r; i++) { // Finding the minimum element if (m[i][0] < min) min = m[i][0]; // Finding the maximum element if (m[i][c-1] > max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while (min < max) { int mid = min + (max - min) / 2; int place = 0; // Find count of elements smaller than or equal to mid for (int i = 0; i < r; ++i) place += upper_bound(m[i], m[i]+c, mid) - m[i]; if (place < desired) min = mid + 1; else max = mid; } return min; } // driver program to check above functions int main() { int r = 3, c = 3; int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; cout << "Median is " << binaryMedian(m, r, c) << endl; return 0; }
constant
nlogn
// C++ program to print Lower // triangular and Upper triangular // matrix of an array #include<iostream> using namespace std; // Function to form // lower triangular matrix void lower(int matrix[3][3], int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i < j) { cout << "0" << " "; } else cout << matrix[i][j] << " "; } cout << endl; } } // Function to form upper triangular matrix void upper(int matrix[3][3], int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i > j) { cout << "0" << " "; } else cout << matrix[i][j] << " "; } cout << endl; } } // Driver Code int main() { int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int row = 3, col = 3; cout << "Lower triangular matrix: \n"; lower(matrix, row, col); cout << "Upper triangular matrix: \n"; upper(matrix, row, col); return 0; }
constant
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; vector<int> spiralOrder(vector<vector<int> >& matrix) { int m = matrix.size(), n = matrix[0].size(); vector<int> ans; if (m == 0) return ans; vector<vector<bool> > seen(m, vector<bool>(n, false)); int dr[] = { 0, 1, 0, -1 }; int dc[] = { 1, 0, -1, 0 }; int x = 0, y = 0, di = 0; // Iterate from 0 to m * n - 1 for (int i = 0; i < m * n; i++) { ans.push_back(matrix[x][y]); // on normal geeksforgeeks ui page it is showing // 'ans.push_back(matrix[x])' which gets copied as // this only and gives error on compilation, seen[x][y] = true; int newX = x + dr[di]; int newY = y + dc[di]; if (0 <= newX && newX < m && 0 <= newY && newY < n && !seen[newX][newY]) { x = newX; y = newY; } else { di = (di + 1) % 4; x += dr[di]; y += dc[di]; } } return ans; } // Driver code int main() { vector<vector<int> > a{ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call for (int x : spiralOrder(a)) { cout << x << " "; } return 0; } // This code is contributed by Yashvendra Singh
linear
linear
// C++ Program to print a matrix spirally #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 void spiralPrint(int m, int n, int a[R][C]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { cout << a[k][i] << " "; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { cout << a[i][n - 1] << " "; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { cout << a[m - 1][i] << " "; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m - 1; i >= k; --i) { cout << a[i][l] << " "; } l++; } } } /* Driver Code */ int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call spiralPrint(R, C, a); return 0; } // This is code is contributed by rathbhupendra
constant
quadratic
// C++. program for the above approach #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 // Function for printing matrix in spiral // form i, j: Start index of matrix, row // and column respectively m, n: End index // of matrix row and column respectively void print(int arr[R][C], int i, int j, int m, int n) { // If i or j lies outside the matrix if (i >= m or j >= n) return; // Print First Row for (int p = j; p < n; p++) cout << arr[i][p] << " "; // Print Last Column for (int p = i + 1; p < m; p++) cout << arr[p][n - 1] << " "; // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) for (int p = n - 2; p >= j; p--) cout << arr[m - 1][p] << " "; // Print First Column, if Last and // First Column are not same if ((n - 1) != j) for (int p = m - 2; p > i; p--) cout << arr[p][j] << " "; print(arr, i + 1, j + 1, m - 1, n - 1); } // Driver Code int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); return 0; } // This Code is contributed by Ankur Goel
constant
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 bool isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } // check if the position is blocked bool isBlocked(int matrix[R][C], int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false; } // DFS code to traverse spirally void spirallyDFSTravserse(int matrix[R][C], int i, int j, int dir, vector<int>& res) { if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push_back(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } // To traverse spirally vector<int> spirallyTraverse(int matrix[R][C]) { vector<int> res; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } // Driver Code int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call vector<int> res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) cout << res[i] << " "; cout << endl; return 0; } // code contributed by Ephi F
constant
quadratic
// C++ program to find unique element in matrix #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 // function that calculate unique element int unique(int mat[R][C], int n, int m) { // declare map for hashing unordered_map<int, int> mp; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) // increase freq of mat[i][j] in map mp[mat[i][j]]++; int flag = false; // print unique element for (auto p : mp) { if (p.second == 1) { cout << p.first << " "; flag = 1; } } if (!flag) { cout << "No unique element in the matrix"; } } // Driver program int main() { int mat[R][C] = { { 1, 2, 3, 20 }, { 5, 6, 20, 25 }, { 1, 3, 5, 6 }, { 6, 7, 8, 15 } }; // function that calculate unique element unique(mat, R, C); return 0; }
quadratic
quadratic
// C++ program to shift k elements in a matrix. #include <bits/stdc++.h> using namespace std; #define N 4 // Function to shift first k elements of // each row of matrix. void shiftMatrixByK(int mat[N][N], int k) { if (k > N) { cout << "shifting is not possible" << endl; return; } int j = 0; while (j < N) { // Print elements from index k for (int i = k; i < N; i++) cout << mat[j][i] << " "; // Print elements before index k for (int i = 0; i < k; i++) cout << mat[j][i] << " "; cout << endl; j++; } } // Driver code int main() { int mat[N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int k = 2; // Function call shiftMatrixByK(mat, k); return 0; }
constant
quadratic
// CPP Program to swap diagonal of a matrix #include <bits/stdc++.h> using namespace std; // size of square matrix #define N 3 // Function to swap diagonal of matrix void swapDiagonal(int matrix[][N]) { for (int i = 0; i < N; i++) swap(matrix[i][i], matrix[i][N - i - 1]); } // Driver Code int main() { int matrix[N][N] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; swapDiagonal(matrix); // Displaying modified matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << matrix[i][j] << " "; cout << endl; } return 0; }
constant
quadratic
// CPP program for finding max path in matrix #include <bits/stdc++.h> #define N 4 #define M 6 using namespace std; // To calculate max path in matrix int findMaxPath(int mat[][M]) { for (int i = 1; i < N; i++) { for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum } } int res = 0; for (int j = 0; j < M; j++) res = max(mat[N-1][j], res); return res; } // Driver program to check findMaxPath int main() { int mat1[N][M] = { { 10, 10, 2, 0, 20, 4 }, { 1, 0, 0, 30, 2, 5 }, { 0, 10, 4, 0, 2, 0 }, { 1, 0, 2, 20, 0, 4 } }; cout << findMaxPath(mat1) << endl; return 0; }
constant
quadratic
// C++ code to move matrix elements // in given direction with add // element with same value #include <bits/stdc++.h> using namespace std; #define MAX 50 // Function to shift the matrix // in the given direction void moveMatrix(char d[], int n, int a[MAX][MAX]) { // For right shift move. if (d[0] == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (auto it = w.begin(); it != w.end(); it++) a[i][j--] = *it; } } // for left shift move else if (d[0] == 'l') { // for each row for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (auto it = w.begin(); it != w.end(); it++) a[i][j++] = *it; } } // for down shift move. else if (d[0] == 'd') { // for each column for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j--][i] = *it; } } // for up shift move else if (d[0] == 'u') { // for each column for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j++][i] = *it; } } } // Driven Program int main() { char d[2] = "l"; int n = 5; int a[MAX][MAX] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << a[i][j] << " "; cout << endl; } return 0; }
linear
quadratic
// C++ implementation to sort the rows // of matrix in ascending order followed by // sorting the columns in descending order #include <bits/stdc++.h> using namespace std; #define MAX_SIZE 10 // function to sort each row of the matrix // according to the order specified by // ascending. void sortByRow(int mat[][MAX_SIZE], int n, bool ascending) { for (int i = 0; i < n; i++) { if (ascending) sort(mat[i], mat[i] + n); else sort(mat[i], mat[i] + n, greater<int>()); } } // function to find transpose of the matrix void transpose(int mat[][MAX_SIZE], int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // swapping element at index (i, j) // by element at index (j, i) swap(mat[i][j], mat[j][i]); } // function to sort the matrix row-wise // and column-wise void sortMatRowAndColWise(int mat[][MAX_SIZE], int n) { // sort rows of mat[][] sortByRow(mat, n, true); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat, n, false); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix void printMat(int mat[][MAX_SIZE], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; } } // Driver program to test above int main() { int n = 3; int mat[n][MAX_SIZE] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; cout << "Original Matrix:\n"; printMat(mat, n); sortMatRowAndColWise(mat, n); cout << "\nMatrix After Sorting:\n"; printMat(mat, n); return 0; }
constant
quadratic
// C++ program to find sum of // middle row and column in matrix #include <iostream> using namespace std; const int MAX = 100; void middlesum(int mat[][MAX], int n) { int row_sum = 0, col_sum = 0; //loop for sum of row for (int i = 0; i < n; i++) row_sum += mat[n / 2][i]; cout << "Sum of middle row = " << row_sum<<endl; //loop for sum of column for (int i = 0; i < n; i++) col_sum += mat[i][n / 2]; cout << "Sum of middle column = " << col_sum; } // Driver function int main() { int mat[][MAX] = {{2, 5, 7}, {3, 7, 2}, {5, 6, 9}}; middlesum(mat, 3); return 0; }
constant
linear
// C++ program showing time difference // in row major and column major access #include <stdio.h> #include <time.h> // taking MAX 10000 so that time difference // can be shown #define MAX 10000 int arr[MAX][MAX] = { 0 }; void rowMajor() { int i, j; // accessing element row wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[i][j]++; } } } void colMajor() { int i, j; // accessing element column wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[j][i]++; } } } // driver code int main() { int i, j; // Time taken by row major order clock_t t = clock(); rowMajor(); t = clock() - t; printf("Row major access time :%f s\n", t / (float)CLOCKS_PER_SEC); // Time taken by column major order t = clock(); colMajor(); t = clock() - t; printf("Column major access time :%f s\n", t / (float)CLOCKS_PER_SEC); return 0; }
quadratic
quadratic
// CPP program to rotate a matrix right by k times #include <iostream> // size of matrix #define M 3 #define N 3 using namespace std; // function to rotate matrix by k times void rotateMatrix(int matrix[][M], int k) { // temporary array of size M int temp[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k to end to starting for (int j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from temporary array to end for (int j = k; j < M; j++) matrix[i][j] = temp[j - k]; } } // function to display the matrix void displayMatrix(int matrix[][M]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << matrix[i][j] << " "; cout << endl; } } // Driver's code int main() { int matrix[N][M] = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); return 0; }
linear
quadratic
// Program to check given matrix // is idempotent matrix or not. #include<bits/stdc++.h> #define N 3 using namespace std; // Function for matrix multiplication. void multiply(int mat[][N], int res[][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { res[i][j] = 0; for (int k = 0; k < N; k++) res[i][j] += mat[i][k] * mat[k][j]; } } } // Function to check idempotent // property of matrix. bool checkIdempotent(int mat[][N]) { // Calculate multiplication of matrix // with itself and store it into res. int res[N][N]; multiply(mat, res); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != res[i][j]) return false; return true; } // Driver function. int main() { int mat[N][N] = {{2, -2, -4}, {-1, 3, 4}, {1, -2, -3}}; // checkIdempotent function call. if (checkIdempotent(mat)) cout << "Idempotent Matrix"; else cout << "Not Idempotent Matrix."; return 0; }
quadratic
cubic
// Program to implement involutory matrix. #include <bits/stdc++.h> #define N 3 using namespace std; // Function for matrix multiplication. void multiply(int mat[][N], int res[][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { res[i][j] = 0; for (int k = 0; k < N; k++) res[i][j] += mat[i][k] * mat[k][j]; } } } // Function to check involutory matrix. bool InvolutoryMatrix(int mat[N][N]) { int res[N][N]; // multiply function call. multiply(mat, res); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (i == j && res[i][j] != 1) return false; if (i != j && res[i][j] != 0) return false; } } return true; } // Driver function. int main() { int mat[N][N] = { { 1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } }; // Function call. If function return // true then if part will execute otherwise // else part will execute. if (InvolutoryMatrix(mat)) cout << "Involutory Matrix"; else cout << "Not Involutory Matrix"; return 0; }
quadratic
cubic
// C++ code to swap the element of first // and last row and display the result #include <iostream> using namespace std; #define n 4 void interchangeFirstLast(int m[][n]) { int rows = n; // swapping of element between first // and last rows for (int i = 0; i < n; i++) { int t = m[0][i]; m[0][i] = m[rows - 1][i]; m[rows - 1][i] = t; } } // Driver code int main() { // input in the array int m[n][n] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; // Function call interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << m[i][j] << " "; cout << endl; } } // This code is contributed by Anant Agarwal.
constant
linear
/* C++ Program to print matrix in Zig-zag pattern*/ #include <iostream> using namespace std; #define C 3 // Utility function to print matrix // in zig-zag form void zigZagMatrix(int arr[][C], int n, int m) { int row = 0, col = 0; // Boolean variable that will true if we // need to increment 'row' value otherwise // false- if increment 'col' value bool row_inc = 0; // Print matrix of lower half zig-zag pattern int mn = min(m, n); for (int len = 1; len <= mn; ++len) { for (int i = 0; i < len; ++i) { cout << arr[row][col] << " "; if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment // col if (row_inc) ++row, --col; else --row, ++col; } if (len == mn) break; // Update row or col value according // to the last increment if (row_inc) ++row, row_inc = false; else ++col, row_inc = true; } // Update the indexes of row and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = 1; } else { if (row == n - 1) ++col; else ++row; row_inc = 0; } // Print the next half zig-zag pattern int MAX = max(m, n) - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (int i = 0; i < len; ++i) { cout << arr[row][col] << " "; if (i + 1 == len) break; // Update row or col value according // to the last increment if (row_inc) ++row, --col; else ++col, --row; } // Update the indexes of row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } } } // Driver code int main() { int matrix[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; zigZagMatrix(matrix, 3, 3); return 0; }
constant
quadratic
// C++ code to // sort 2D matrix row-wise #include<bits/stdc++.h> using namespace std; void sortRowWise(int m[][4], int r, int c) { // loop for rows of matrix for (int i = 0; i < r; i++) { // loop for column of matrix for (int j = 0; j < c; j++) { // loop for comparison and swapping for (int k = 0; k < c - j - 1; k++) { if (m[i][k] > m[i][k + 1]) { // swapping of elements swap(m[i][k], m[i][k + 1]); } } } } // printing the sorted matrix for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout << m[i][j] << " "; cout << endl; } } // Driver code int main() { int m[][4] = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; int c = sizeof(m[0]) / sizeof(m[0][0]); int r = sizeof(m) / sizeof(m[0]); sortRowWise(m, r, c); return 0; } // This code is contributed by Rutvik_56
constant
quadratic
// C++ code to sort 2D // matrix row-wise #include <bits/stdc++.h> using namespace std; #define M 4 #define N 4 int sortRowWise(int m[M][N]) { // One by one sort // individual rows. for (int i = 0; i < M; i++) sort(m[i], m[i] + N); // Printing the sorted matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) cout << (m[i][j]) << " "; cout << endl; } } // Driver code int main() { int m[M][N] = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; sortRowWise(m); } // This code is contributed by gauravrajput1
constant
quadratic
// C++ code to check Markov Matrix #include <iostream> using namespace std; #define n 3 bool checkMarkov(double m[][n]) { // outer loop to access rows // and inner to access columns for (int i = 0; i <n; i++) { // Find sum of current row double sum = 0; for (int j = 0; j < n; j++) sum = sum + m[i][j]; if (sum != 1) return false; } return true; } // Driver Code int main() { // Matrix to check double m[3][3] = { { 0, 0, 1 }, { 0.5, 0, 0.5 }, { 1, 0, 0 } }; // calls the function check() if (checkMarkov(m)) cout << " yes "; else cout << " no "; } // This code is contributed by Anant Agarwal.
constant
quadratic
// Program to check matrix is diagonal matrix or not. #include <bits/stdc++.h> #define N 4 using namespace std; // Function to check matrix // is diagonal matrix or not. bool isDiagonalMatrix(int mat[N][N]) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // condition to check other elements // except main diagonal are zero or not. if ((i != j) && (mat[i][j] != 0)) return false; return true; } // Driver function int main() { int mat[N][N] = { { 4, 0, 0, 0 }, { 0, 7, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 1 } }; if (isDiagonalMatrix(mat)) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
constant
quadratic
// Program to check matrix is scalar matrix or not. #include <bits/stdc++.h> #define N 4 using namespace std; // Function to check matrix is scalar matrix or not. bool isScalarMatrix(int mat[N][N]) { // Check all elements except main diagonal are // zero or not. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if ((i != j) && (mat[i][j] != 0)) return false; // Check all diagonal elements are same or not. for (int i = 0; i < N - 1; i++) if (mat[i][i] != mat[i + 1][i + 1]) return false; return true; } // Driver function int main() { int mat[N][N] = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; // Function call if (isScalarMatrix(mat)) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
constant
quadratic
// C++ implementation to sort the matrix row-wise // and column-wise #include <bits/stdc++.h> using namespace std; #define MAX_SIZE 10 // function to sort each row of the matrix void sortByRow(int mat[MAX_SIZE][MAX_SIZE], int n) { for (int i = 0; i < n; i++) // sorting row number 'i' sort(mat[i], mat[i] + n); } // function to find transpose of the matrix void transpose(int mat[MAX_SIZE][MAX_SIZE], int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // swapping element at index (i, j) // by element at index (j, i) swap(mat[i][j], mat[j][i]); } // function to sort the matrix row-wise // and column-wise void sortMatRowAndColWise(int mat[MAX_SIZE][MAX_SIZE], int n) { // sort rows of mat[][] sortByRow(mat, n); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] sortByRow(mat, n); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix void printMat(int mat[MAX_SIZE][MAX_SIZE], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; } } // Driver program to test above int main() { int mat[MAX_SIZE][MAX_SIZE] = { { 4, 1, 3 }, { 9, 6, 8 }, { 5, 2, 7 } }; int n = 3; cout << "Original Matrix:\n"; printMat(mat, n); sortMatRowAndColWise(mat, n); cout << "\nMatrix After Sorting:\n"; printMat(mat, n); return 0; }
constant
quadratic
// C++ Program to count islands in boolean 2D matrix #include <bits/stdc++.h> using namespace std; #define ROW 5 #define COL 5 // A function to check if a given // cell (row, col) can be included in DFS int isSafe(int M[][COL], int row, int col, bool visited[][COL]) { // row number is in range, column // number is in range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]); } // A utility function to do DFS for a // 2D boolean matrix. It only considers // the 8 neighbours as adjacent vertices void DFS(int M[][COL], int row, int col, bool visited[][COL]) { // These arrays are used to get // row and column numbers of 8 // neighbours of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited); } // The main function that returns // count of islands in a given boolean // 2D matrix int countIslands(int M[][COL]) { // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize count as 0 and // traverse through the all cells of // given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new island found // Visit all cells in this island. DFS(M, i, j, visited); // and increment island count ++count; } return count; } // Driver code int main() { int M[][COL] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << "Number of islands is: " << countIslands(M); return 0; } // This is code is contributed by rathbhupendra
quadratic
quadratic
// C++Program to count islands in boolean 2D matrix #include <bits/stdc++.h> using namespace std; // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices void DFS(vector<vector<int> >& M, int i, int j, int ROW, int COL) { // Base condition // if i less than 0 or j less than 0 or i greater than // ROW-1 or j greater than COL- or if M[i][j] != 1 then // we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); // right side traversal DFS(M, i - 1, j, ROW, COL); // left side traversal DFS(M, i, j + 1, ROW, COL); // upward side traversal DFS(M, i, j - 1, ROW, COL); // downward side traversal DFS(M, i + 1, j + 1, ROW, COL); // upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); // downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); // downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); // upward-left side traversal } } int countIslands(vector<vector<int> >& M) { int ROW = M.size(); int COL = M[0].size(); int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i][j] == 1) { count++; DFS(M, i, j, ROW, COL); // traversal starts // from current cell } } } return count; } // Driver Code int main() { vector<vector<int> > M = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << "Number of islands is: " << countIslands(M); return 0; } // This code is contributed by ajaymakvana. // Code improved by Animesh Singh
quadratic
quadratic
// C++ Program to print Magic square // of Doubly even order #include<iostream> using namespace std; // Function for calculating Magic square void doublyEven( int n ) { int arr[n][n], i, j; // filling matrix with its count value // starting from 1; for ( i = 0; i < n; i++) for ( j = 0; j < n; j++) arr[i][j] = (n*i) + j + 1; // change value of Array elements // at fix location as per rule // (n*n+1)-arr[i][j] // Top Left corner of Matrix // (order (n/4)*(n/4)) for ( i = 0; i < n/4; i++) for ( j = 0; j < n/4; j++) arr[i][j] = (n*n + 1) - arr[i][j]; // Top Right corner of Matrix // (order (n/4)*(n/4)) for ( i = 0; i < n/4; i++) for ( j = 3 * (n/4); j < n; j++) arr[i][j] = (n*n + 1) - arr[i][j]; // Bottom Left corner of Matrix // (order (n/4)*(n/4)) for ( i = 3 * n/4; i < n; i++) for ( j = 0; j < n/4; j++) arr[i][j] = (n*n+1) - arr[i][j]; // Bottom Right corner of Matrix // (order (n/4)*(n/4)) for ( i = 3 * n/4; i < n; i++) for ( j = 3 * n/4; j < n; j++) arr[i][j] = (n*n + 1) - arr[i][j]; // Centre of Matrix (order (n/2)*(n/2)) for ( i = n/4; i < 3 * n/4; i++) for ( j = n/4; j < 3 * n/4; j++) arr[i][j] = (n*n + 1) - arr[i][j]; // Printing the magic-square for (i = 0; i < n; i++) { for ( j = 0; j < n; j++) cout << arr[i][j] << " "; cout << "\n"; } } // driver program int main() { int n=8; doublyEven(n); //Function call return 0; }
quadratic
quadratic
// C++ program to generate odd sized magic squares #include <bits/stdc++.h> using namespace std; // A function to generate odd sized magic squares void generateSquare(int n) { int magicSquare[n][n]; // set all slots as 0 memset(magicSquare, 0, sizeof(magicSquare)); // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number // is goes to out of square's upper side if (i < 0) i = n - 1; } if (magicSquare[i][j]) // 2nd condition { j -= 2; i++; continue; } else magicSquare[i][j] = num++; // set number j++; i--; // 1st condition } // Print magic square cout << "The Magic Square for n=" << n << ":\nSum of " "each row or column " << n * (n * n + 1) / 2 << ":\n\n"; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) // setw(7) is used so that the matrix gets // printed in a proper square fashion. cout << setw(4) << magicSquare[i][j] << " "; cout << endl; } } // Driver code int main() { // Works only when n is odd int n = 7; generateSquare(n); return 0; } // This code is contributed by rathbhupendra
quadratic
quadratic
// C++ program to check whether a given // matrix is magic matrix or not #include <bits/stdc++.h> # define my_sizeof(type) ((char *)(&type+1)-(char*)(&type)) using namespace std; // Returns true if mat[][] is magic // square, else returns false. bool isMagicSquare(int mat[][3]) { int n = my_sizeof(mat)/my_sizeof(mat[0]); // calculate the sum of // the prime diagonal int i=0,j=0; // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0, sumd2=0; for (i = 0; i < n; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1 += mat[i][i]; sumd2 += mat[i][n-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // For sums of Rows for (i = 0; i < n; i++) { int rowSum = 0, colSum = 0; for (j = 0; j < n; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true; } // driver program to // test above function int main() { int mat[3][3] = {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) cout << "Magic Square"; else cout << "Not a magic Square"; return 0; }
constant
quadratic
// C++ program to check whether a given // matrix is magic matrix or not #include <bits/stdc++.h> # define my_sizeof(type) ((char *)(&type+1)-(char*)(&type)) using namespace std; // Returns true if mat[][] is magic // square, else returns false. bool isMagicSquare(int mat[][3]) { int n = my_sizeof(mat)/my_sizeof(mat[0]); // calculate the sum of // the prime diagonal int i=0,j=0; // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0, sumd2=0; for (i = 0; i < n; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1 += mat[i][i]; sumd2 += mat[i][n-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // For sums of Rows for (i = 0; i < n; i++) { int rowSum = 0, colSum = 0; for (j = 0; j < n; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true; } // driver program to // test above function int main() { int mat[3][3] = {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) cout << "Magic Square"; else cout << "Not a magic Square"; return 0; }
constant
quadratic
// C++ code to find the Kronecker Product of two // matrices and stores it as matrix C #include <bits/stdc++.h> using namespace std; // rowa and cola are no of rows and columns // of matrix A // rowb and colb are no of rows and columns // of matrix B const int cola = 2, rowa = 3, colb = 3, rowb = 2; // Function to computes the Kronecker Product // of two matrices void Kroneckerproduct(int A[][cola], int B[][colb]) { int C[rowa * rowb][cola * colb]; // i loops till rowa for (int i = 0; i < rowa; i++) { // k loops till rowb for (int k = 0; k < cola; k++) { // j loops till cola for (int j = 0; j < rowb; j++) { // l loops till colb for (int l = 0; l < colb; l++) { // Each element of matrix A is // multiplied by whole Matrix B // resp and stored as Matrix C C[i * rowb + k][j * colb + l] = A[i][j] * B[k][l]; } } } } for (int i = 0; i < rowa * rowb; i++) { for (int j = 0; j < cola * colb; j++) { cout << C[i][j] << " "; } cout << endl; } } // Driver Code int main() { int A[3][2] = { { 1, 2 }, { 3, 4 }, { 1, 0 } }, B[2][3] = { { 0, 5, 2 }, { 6, 7, 3 } }; Kroneckerproduct(A, B); return 0; } // This code is contributed by shubhamsingh10
np
np
// C++ implementation to count sub-matrices having sum // divisible by the value 'k' #include <bits/stdc++.h> using namespace std; #define SIZE 10 // function to count all sub-arrays divisible by k int subCount(int arr[], int n, int k) { // create auxiliary hash array to count frequency // of remainders int mod[k]; memset(mod, 0, sizeof(mod)); // Traverse original array and compute cumulative // sum take remainder of this current cumulative // sum and increase count by 1 for this remainder // in mod[] array int cumSum = 0; for (int i = 0; i < n; i++) { cumSum += arr[i]; // as the sum can be negative, taking modulo // twice mod[((cumSum % k) + k) % k]++; } int result = 0; // Initialize result // Traverse mod[] for (int i = 0; i < k; i++) // If there are more than one prefix subarrays // with a particular mod value. if (mod[i] > 1) result += (mod[i] * (mod[i] - 1)) / 2; // add the subarrays starting from the arr[i] // which are divisible by k itself result += mod[0]; return result; } // function to count all sub-matrices having sum // divisible by the value 'k' int countSubmatrix(int mat[SIZE][SIZE], int n, int k) { // Variable to store the final output int tot_count = 0; int left, right, i; int temp[n]; // Set the left column for (left = 0; left < n; left++) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left column // set by outer loop for (right = left; right < n; right++) { // Calculate sum between current left // and right for every row 'i' for (i = 0; i < n; ++i) temp[i] += mat[i][right]; // Count number of subarrays in temp[] // having sum divisible by 'k' and then // add it to 'tot_count' tot_count += subCount(temp, n, k); } } // required count of sub-matrices having sum // divisible by 'k' return tot_count; } // Driver program to test above int main() { int mat[][SIZE] = { { 5, -1, 6 }, { -2, 3, 8 }, { 7, 4, -9 } }; int n = 3, k = 4; cout << "Count = " << countSubmatrix(mat, n, k); return 0; }
linear
cubic
// CPP Program to check whether given matrix // is Diagonally Dominant Matrix. #include <bits/stdc++.h> #define N 3 using namespace std; // check the given matrix is Diagonally // Dominant Matrix or not. bool isDDM(int m[N][N], int n) { // for each row for (int i = 0; i < n; i++) { // for each column, finding sum of each row. int sum = 0; for (int j = 0; j < n; j++) sum += abs(m[i][j]); // removing the diagonal element. sum -= abs(m[i][i]); // checking if diagonal element is less // than sum of non-diagonal element. if (abs(m[i][i]) < sum) return false; } return true; } // Driven Program int main() { int n = 3; int m[N][N] = { { 3, -2, 1 }, { 1, -3, 2 }, { -1, 2, 4 } }; (isDDM(m, n)) ? (cout << "YES") : (cout << "NO"); return 0; }
constant
quadratic
// C++ Program to Find minimum number of operation required // such that sum of elements on each row and column becomes // same*/ #include <bits/stdc++.h> using namespace std; // Function to find minimum operation required to make sum // of each row and column equals int findMinOpeartion(int matrix[][2], int n) { // Initialize the sumRow[] and sumCol[] array to 0 int sumRow[n], sumCol[n]; memset(sumRow, 0, sizeof(sumRow)); memset(sumCol, 0, sizeof(sumCol)); // Calculate sumRow[] and sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = max(maxSum, sumRow[i]); maxSum = max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment required in either row or // column int diff = min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in corresponding cell, sumRow[] // and sumCol[] array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count variable count += diff; // If ith row satisfied, increment ith value for // next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count; } // Utility function to print matrix void printMatrix(int matrix[][2], int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) cout << matrix[i][j] << " "; cout << "\n"; } } // Driver code int main() { int matrix[][2] = { { 1, 2 }, { 3, 4 } }; cout << findMinOpeartion(matrix, 2) << "\n"; printMatrix(matrix, 2); return 0; } // This code is contributed by Sania Kumari Gupta
linear
quadratic
// CPP program to find the frequency of k // in matrix where m(i, j)=i+j #include <bits/stdc++.h> using namespace std; int find(int n, int k) { if (n + 1 >= k) return (k - 1); else return (2 * n + 1 - k); } // Driver Code int main() { int n = 4, k = 7; int freq = find(n, k); if (freq < 0) cout << " element not exist \n "; else cout << " Frequency of " << k << " is " << freq << "\n"; return 0; }
constant
constant
// CPP program to print given number of 1's, // 2's, 3's ....k's in zig-zag way. #include <bits/stdc++.h> using namespace std; // function that prints given number of 1's, // 2's, 3's ....k's in zig-zag way. void ZigZag(int rows, int columns, int numbers[]) { int k = 0; // two-dimensional array to store numbers. int arr[rows][columns]; for (int i=0; i<rows; i++) { // for even row. if (i%2==0) { // for each column. for (int j=0; j<columns and numbers[k]>0; j++) { // storing element. arr[i][j] = k+1; // decrement element at // kth index. numbers[k]--; // if array contains zero // then increment index to // make this next index if (numbers[k] == 0) k++; } } // for odd row. else { // for each column. for (int j=columns-1; j>=0 and numbers[k]>0; j--) { // storing element. arr[i][j] = k+1; // decrement element // at kth index. numbers[k]--; // if array contains zero then // increment index to make this // next index. if (numbers[k]==0) k++; } } } // printing the stored elements. for (int i=0;i<rows;i++) { for (int j=0;j<columns;j++) cout << arr[i][j] << " "; cout << endl; } } // Driver code for above function. int main() { int rows = 4; int columns = 5; int Numbers[] = {3, 4, 2, 2, 3, 1, 5}; ZigZag(rows, columns, Numbers); return 0; }
quadratic
quadratic
// C++ program to find out the maximum product // in the matrix which four elements are // adjacent to each other in one direction #include <bits/stdc++.h> using namespace std; const int n = 5; // function to find max product int FindMaxProduct(int arr[][n], int n) { int max = 0, result; // iterate the rows. for (int i = 0; i < n; i++) { // iterate the columns. for (int j = 0; j < n; j++) { // check the maximum product // in horizontal row. if ((j - 3) >= 0) { result = arr[i][j] * arr[i][j - 1] * arr[i][j - 2] * arr[i][j - 3]; if (max < result) max = result; } // check the maximum product // in vertical row. if ((i - 3) >= 0) { result = arr[i][j] * arr[i - 1][j] * arr[i - 2][j] * arr[i - 3][j]; if (max < result) max = result; } // check the maximum product in // diagonal (going through down - right) if ((i - 3) >= 0 && (j - 3) >= 0) { result = arr[i][j] * arr[i - 1][j - 1] * arr[i - 2][j - 2] * arr[i - 3][j - 3]; if (max < result) max = result; } // check the maximum product in // diagonal (going through up - right) if ((i - 3) >= 0 && (j - 3) <= 0) { result = arr[i][j] * arr[i - 1][j + 1] * arr[i - 2][j + 2] * arr[i - 3][j + 3]; if (max < result) max = result; } } } return max; } // Driver code int main() { /* int arr[][4] = {{6, 2, 3, 4}, {5, 4, 3, 1}, {7, 4, 5, 6}, {8, 3, 1, 0}};*/ /* int arr[][5] = {{1, 2, 1, 3, 4}, {5, 6, 3, 9, 2}, {7, 8, 8, 1, 2}, {1, 0, 7, 9, 3}, {3, 0, 8, 4, 9}};*/ int arr[][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 1}, {2, 3, 4, 5, 6}, {7, 8, 9, 1, 0}, {9, 6, 4, 2, 3}}; cout << FindMaxProduct(arr, n); return 0; }
constant
quadratic
// C++ implementation of the above approach #include <bits/stdc++.h> using namespace std; int maxPro(int a[6][5], int n, int m, int k) { int maxi(1), mp(1); for (int i = 0; i < n; ++i) { // Window Product for each row. int wp(1); for (int l = 0; l < k; ++l) { wp *= a[i][l]; } // Maximum window product for each row mp = wp; for (int j = k; j < m; ++j) { wp = wp * a[i][j] / a[i][j - k]; // Global maximum window product maxi = max(maxi,max(mp,wp)); } } return maxi; } // Driver Code int main() { int n = 6, m = 5, k = 4; int a[6][5] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 1 }, { 2, 3, 4, 5, 6 }, { 7, 8, 9, 1, 0 }, { 9, 6, 4, 2, 3 }, { 1, 1, 2, 1, 1 } }; cout << maxPro(a, n, m, k); return 0; }
constant
quadratic
// Program to check lower // triangular matrix. #include <bits/stdc++.h> #define N 4 using namespace std; // Function to check matrix is in // lower triangular form or not. bool isLowerTriangularMatrix(int mat[N][N]) { for (int i = 0; i < N-1; i++) for (int j = i + 1; j < N; j++) if (mat[i][j] != 0) return false; return true; } // Driver function. int main() { int mat[N][N] = { { 1, 0, 0, 0 }, { 1, 4, 0, 0 }, { 4, 6, 2, 0 }, { 0, 4, 7, 6 } }; // Function call if (isLowerTriangularMatrix(mat)) cout << "Yes"; else cout << "No"; return 0; }
constant
quadratic
// Program to check upper triangular matrix. #include <bits/stdc++.h> #define N 4 using namespace std; // Function to check matrix is in upper triangular // form or not. bool isUpperTriangularMatrix(int mat[N][N]) { for (int i = 1; i < N; i++) for (int j = 0; j < i; j++) if (mat[i][j] != 0) return false; return true; } // Driver function. int main() { int mat[N][N] = { { 1, 3, 5, 3 }, { 0, 4, 6, 2 }, { 0, 0, 2, 5 }, { 0, 0, 0, 6 } }; if (isUpperTriangularMatrix(mat)) cout << "Yes"; else cout << "No"; return 0; }
constant
quadratic
// C++ Program to Find the frequency // of even and odd numbers in a matrix #include<bits/stdc++.h> using namespace std; #define MAX 100 // function for calculating frequency void freq(int ar[][MAX], int m, int n) { int even = 0, odd = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // modulo by 2 to check // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers printf(" Frequency of odd number = %d \n", odd); printf(" Frequency of even number = %d \n", even); } // Driver code int main() { int m = 3, n = 3; int array[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; freq(array, m, n); return 0; }
constant
quadratic
// C++ Program to check if the center // element is equal to the individual // sum of all the half diagonals #include <stdio.h> #include<bits/stdc++.h> using namespace std; const int MAX = 100; // Function to Check center element // is equal to the individual // sum of all the half diagonals bool HalfDiagonalSums(int mat[][MAX], int n) { // Find sums of half diagonals int diag1_left = 0, diag1_right = 0; int diag2_left = 0, diag2_right = 0; for (int i = 0, j = n - 1; i < n; i++, j--) { if (i < n/2) { diag1_left += mat[i][i]; diag2_left += mat[j][i]; } else if (i > n/2) { diag1_right += mat[i][i]; diag2_right += mat[j][i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[n/2][n/2]); } // Driver code int main() { int a[][MAX] = { { 2, 9, 1, 4, -2}, { 6, 7, 2, 11, 4}, { 4, 2, 9, 2, 4}, { 1, 9, 2, 4, 4}, { 0, 2, 4, 2, 5} }; cout << ( HalfDiagonalSums(a, 5) ? "Yes" : "No" ); return 0; }
constant
linear
// C++ program to print Identity Matrix #include<bits/stdc++.h> using namespace std; int Identity(int num) { int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) cout << 1 << " "; else cout << 0 << " "; } cout << endl; } return 0; } // Driver Code int main() { int size = 5; Identity(size); return 0; } // This code is contributed by shubhamsingh10
constant
quadratic
// CPP program to check if a given matrix is identity #include<iostream> using namespace std; const int MAX = 100; bool isIdentity(int mat[][MAX], int N) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true; } // Driver Code int main() { int N = 4; int mat[][MAX] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) cout << "Yes "; else cout << "No "; return 0; }
constant
quadratic
// CPP Program to implement matrix // for swapping the upper diagonal // elements with lower diagonal // elements of matrix. #include <bits/stdc++.h> #define n 4 using namespace std; // Function to swap the diagonal // elements in a matrix. void swapUpperToLower(int arr[n][n]) { // Loop for swap the elements of matrix. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << arr[i][j] << " "; cout << endl; } } // Driver function to run the program int main() { int arr[n][n] = { { 2, 3, 5, 6 }, { 4, 5, 7, 9 }, { 8, 6, 4, 9 }, { 1, 3, 5, 6 } }; // Function call swapUpperToLower(arr); return 0; }
constant
quadratic
// CPP program to find sparse matrix rep- // resentation using CSR #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef std::vector<int> vi; typedef vector<vector<int> > matrix; // Utility Function to print a Matrix void printMatrix(const matrix& M) { int m = M.size(); int n = M[0].size(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << M[i][j] << " "; cout << endl; } } // Utility Function to print A, IA, JA vectors // with some decoration. void printVector(const vi& V, char* msg) { cout << msg << "[ "; for_each(V.begin(), V.end(), [](int a) { cout << a << " "; }); cout << "]" << endl; } // Generate the three vectors A, IA, JA void sparesify(const matrix& M) { int m = M.size(); int n = M[0].size(), i, j; vi A; vi IA = { 0 }; // IA matrix has N+1 rows vi JA; int NNZ = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (M[i][j] != 0) { A.push_back(M[i][j]); JA.push_back(j); // Count Number of Non Zero // Elements in row i NNZ++; } } IA.push_back(NNZ); } printMatrix(M); printVector(A, (char*)"A = "); printVector(IA, (char*)"IA = "); printVector(JA, (char*)"JA = "); } // Driver code int main() { matrix M = { { 0, 0, 0, 0, 1 }, { 5, 8, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 0, 6, 0, 0, 1 }, }; sparesify(M); return 0; }
linear
quadratic
// Simple CPP program to find mirror of // matrix across diagonal. #include <bits/stdc++.h> using namespace std; const int MAX = 100; void imageSwap(int mat[][MAX], int n) { // for diagonal which start from at // first row of matrix int row = 0; // traverse all top right diagonal for (int j = 0; j < n; j++) { // here we use stack for reversing // the element of diagonal stack<int> s; int i = row, k = j; while (i < n && k >= 0) s.push(mat[i++][k--]); // push all element back to matrix // in reverse order i = row, k = j; while (i < n && k >= 0) { mat[i++][k--] = s.top(); s.pop(); } } // do the same process for all the // diagonal which start from last // column int column = n - 1; for (int j = 1; j < n; j++) { // here we use stack for reversing // the elements of diagonal stack<int> s; int i = j, k = column; while (i < n && k >= 0) s.push(mat[i++][k--]); // push all element back to matrix // in reverse order i = j; k = column; while (i < n && k >= 0) { mat[i++][k--] = s.top(); s.pop(); } } } // Utility function to print a matrix void printMatrix(int mat[][MAX], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; } } // driver program to test above function int main() { int mat[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int n = 4; imageSwap(mat, n); printMatrix(mat, n); return 0; }
linear
quadratic
// Efficient CPP program to find mirror of // matrix across diagonal. #include <bits/stdc++.h> using namespace std; const int MAX = 100; void imageSwap(int mat[][MAX], int n) { // traverse a matrix and swap // mat[i][j] with mat[j][i] for (int i = 0; i < n; i++) for (int j = 0; j <= i; j++) mat[i][j] = mat[i][j] + mat[j][i] - (mat[j][i] = mat[i][j]); } // Utility function to print a matrix void printMatrix(int mat[][MAX], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; } } // driver program to test above function int main() { int mat[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int n = 4; imageSwap(mat, n); printMatrix(mat, n); return 0; }
constant
quadratic
// A brute force approach based CPP program to // find if there is a rectangle with 1 as corners. #include <bits/stdc++.h> using namespace std; // Returns true if there is a rectangle with // 1 as corners. bool isRectangle(const vector<vector<int> >& m) { // finding row and column size int rows = m.size(); if (rows == 0) return false; int columns = m[0].size(); // scanning the matrix for (int y1 = 0; y1 < rows; y1++) for (int x1 = 0; x1 < columns; x1++) // if any index found 1 then try // for all rectangles if (m[y1][x1] == 1) for (int y2 = y1 + 1; y2 < rows; y2++) for (int x2 = x1 + 1; x2 < columns; x2++) if (m[y1][x2] == 1 && m[y2][x1] == 1 && m[y2][x2] == 1) return true; return false; } // Driver code int main() { vector<vector<int> > mat = { { 1, 0, 0, 1, 0 }, { 0, 0, 1, 0, 1 }, { 0, 0, 0, 1, 0 }, { 1, 0, 1, 0, 1 } }; if (isRectangle(mat)) cout << "Yes"; else cout << "No"; }
constant
quadratic
// An efficient approach based CPP program to // find if there is a rectangle with 1 as // corners. #include <bits/stdc++.h> using namespace std; // Returns true if there is a rectangle with // 1 as corners. bool isRectangle(const vector<vector<int> >& matrix) { // finding row and column size int rows = matrix.size(); if (rows == 0) return false; int columns = matrix[0].size(); // map for storing the index of combination of 2 1's unordered_map<int, unordered_set<int> > table; // scanning from top to bottom line by line for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns - 1; ++j) { for (int k = j + 1; k < columns; ++k) { // if found two 1's in a column if (matrix[i][j] == 1 && matrix[i][k] == 1) { // check if there exists 1's in same // row previously then return true // we don't need to check (j, k) pair // and again (k, j) pair because we always // store pair in ascending order and similarly // check in ascending order, i.e. j always less // than k. if (table.find(j) != table.end() && table[j].find(k) != table[j].end()) return true; // store the indexes in hashset table[j].insert(k); } } } } return false; } // Driver code int main() { vector<vector<int> > mat = { { 1, 0, 0, 1, 0 }, { 0, 1, 1, 1, 1 }, { 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 0 } }; if (isRectangle(mat)) cout << "Yes"; else cout << "No"; } // This code is improved by Gautam Agrawal
quadratic
quadratic
// C++ implementation comes from: // https://github.com/MichaelWehar/FourCornersProblem // Written by Niteesh Kumar and Michael Wehar // References: // [1] F. Mráz, D. Prusa, and M. Wehar. // Two-dimensional Pattern Matching against // Basic Picture Languages. CIAA 2019. // [2] D. Prusa and M. Wehar. Complexity of // Searching for 2 by 2 Submatrices in Boolean // Matrices. DLT 2020. #include <bits/stdc++.h> using namespace std; bool searchForRectangle(int rows, int cols, vector<vector<int>> mat) { // Make sure that matrix is non-trivial if (rows < 2 || cols < 2) { return false; } // Create map int num_of_keys; map<int, vector<int>> adjsList; if (rows >= cols) { // Row-wise num_of_keys = rows; // Convert each row into vector of col indexes for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (mat[i][j]) { adjsList[i].push_back(j); } } } } else { // Col-wise num_of_keys = cols; // Convert each col into vector of row indexes for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (mat[i][j]) { adjsList[j].push_back(i); } } } } // Search for a rectangle whose four corners are 1's map<pair<int, int>, int> pairs; for (int i = 0; i < num_of_keys; i++) { vector<int> values = adjsList[i]; int size = values.size(); for (int j = 0; j < size - 1; j++) { for (int k = j + 1; k < size; k++) { pair<int, int> temp = make_pair(values[j], values[k]); if (pairs.find(temp) != pairs.end()) { return true; } else { pairs[temp] = i; } } } } return false; } // Driver code int main() { vector<vector<int> > mat = { { 1, 0, 0, 1, 0 }, { 0, 1, 1, 1, 1 }, { 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 0 } }; if (searchForRectangle(4, 5, mat)) cout << "Yes"; else cout << "No"; }
quadratic
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; void findend(int i,int j, vector<vector<int>> &a, vector<vector<int>> &output,int index) { int x = a.size(); int y = a[0].size(); // flag to check column edge case, // initializing with 0 int flagc = 0; // flag to check row edge case, // initializing with 0 int flagr = 0; int n, m; for (m = i; m < x; m++) { // loop breaks where first 1 encounters if (a[m][j] == 1) { flagr = 1; // set the flag break; } // pass because already processed if (a[m][j] == 5) continue; for (n = j; n < y; n++) { // loop breaks where first 1 encounters if (a[m][n] == 1) { flagc = 1; // set the flag break; } // fill rectangle elements with any // number so that we can exclude // next time a[m][n] = 5; } } if (flagr == 1) output[index].push_back(m-1); else // when end point touch the boundary output[index].push_back(m); if (flagc == 1) output[index].push_back(n-1); else // when end point touch the boundary output[index].push_back(n); } void get_rectangle_coordinates(vector<vector<int>> a) { // retrieving the column size of array int size_of_array = a.size(); // output array where we are going // to store our output vector<vector<int>> output; // It will be used for storing start // and end location in the same index int index = -1; for (int i = 0; i < size_of_array; i++) { for (int j = 0; j < a[0].size(); j++) { if (a[i][j] == 0) { // storing initial position // of rectangle output.push_back({i, j}); // will be used for the // last position index = index + 1; findend(i, j, a, output, index); } } } cout << "["; int aa = 2, bb = 0; for(auto i:output) { bb = 3; cout << "["; for(int j:i) { if(bb) cout << j << ", "; else cout << j; bb--; } cout << "]"; if(aa) cout << ", "; aa--; } cout << "]"; } // Driver code int main() { vector<vector<int>> tests = { {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 0, 0, 0, 1}, {1, 0, 1, 0, 0, 0, 1}, {1, 0, 1, 1, 1, 1, 1}, {1, 0, 1, 0, 0, 0, 0}, {1, 1, 1, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1} }; get_rectangle_coordinates(tests); return 0; } // This code is contributed by mohit kumar 29.
quadratic
quadratic
// 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; }
quadratic
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; }
constant
quadratic
// 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)
constant
quadratic
// 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)
constant
linear
#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
quadratic
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
constant
quadratic
#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; }
constant
quadratic
#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; }
linear
quadratic
// 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; }
constant
quadratic
// 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; }
constant
quadratic
// 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; }
linear
quadratic
// 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; }
constant
linear
// 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"; }
constant
quadratic
// 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; }
constant
linear
#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; }
constant
linear
// 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; }
constant
linear
// 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; }
quadratic
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; }
constant
quadratic
// 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.
quadratic
linear
// CPP program to find number of possible moves of knight #include <bits/stdc++.h> #define n 4 #define m 4 using namespace std; // To calculate possible moves int findPossibleMoves(int mat[n][m], int p, int q) { // All possible moves of a knight int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible move is valid or not for (int i = 0; i < 8; i++) { // Position of knight after move int x = p + X[i]; int y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count++; } // Return number of possible moves return count; } // Driver program to check findPossibleMoves() int main() { int mat[n][m] = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 } }; int p = 2, q = 2; cout << findPossibleMoves(mat, p, q); return 0; }
constant
constant
// A simple C++ program to find sum of diagonals #include <bits/stdc++.h> using namespace std; const int MAX = 100; void printDiagonalSums(int mat[][MAX], int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) principal += mat[i][j]; // Condition for secondary diagonal if ((i + j) == (n - 1)) secondary += mat[i][j]; } } cout << "Principal Diagonal:" << principal << endl; cout << "Secondary Diagonal:" << secondary << endl; } // Driver code int main() { int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); return 0; }
constant
quadratic
// An efficient C++ program to find sum of diagonals #include <bits/stdc++.h> using namespace std; const int MAX = 100; void printDiagonalSums(int mat[][MAX], int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { principal += mat[i][i]; secondary += mat[i][n - i - 1]; } cout << "Principal Diagonal:" << principal << endl; cout << "Secondary Diagonal:" << secondary << endl; } // Driver code int main() { int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); return 0; }
constant
linear
// C++ program to print boundary element of // matrix. #include <bits/stdc++.h> using namespace std; const int MAX = 100; void printBoundary(int a[][MAX], int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0 || i == n - 1 || j == n - 1) cout << a[i][j] << " "; else cout << " " << " "; } cout << "\n"; } } // Driver code int main() { int a[4][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; // Function call printBoundary(a, 4, 4); return 0; }
constant
quadratic
// C++ program to find sum of boundary elements // of matrix. #include <bits/stdc++.h> using namespace std; const int MAX = 100; int getBoundarySum(int a[][MAX], int m, int n) { long long int sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) sum += a[i][j]; else if (i == m - 1) sum += a[i][j]; else if (j == 0) sum += a[i][j]; else if (j == n - 1) sum += a[i][j]; } } return sum; } // Driver code int main() { int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; // Function call long long int sum = getBoundarySum(a, 4, 4); cout << "Sum of boundary elements is " << sum; return 0; }
constant
quadratic
// C++ program to print a matrix in spiral // form. #include <iostream> using namespace std; const int MAX = 100; void printSpiral(int mat[][MAX], int r, int c) { int i, a = 0, b = 2; int low_row = (0 > a) ? 0 : a; int low_column = (0 > b) ? 0 : b - 1; int high_row = ((a + 1) >= r) ? r - 1 : a + 1; int high_column = ((b + 1) >= c) ? c - 1 : b + 1; while ((low_row > 0 - r && low_column > 0 - c)) { for (i = low_column + 1; i <= high_column && i < c && low_row >= 0; ++i) cout << mat[low_row][i] << " "; low_row -= 1; for (i = low_row + 2; i <= high_row && i < r && high_column < c; ++i) cout << mat[i][high_column] << " "; high_column += 1; for (i = high_column - 2; i >= low_column && i >= 0 && high_row < r; --i) cout << mat[high_row][i] << " "; high_row += 1; for (i = high_row - 2; i > low_row && i >= 0 && low_column >= 0; --i) cout << mat[i][low_column] << " "; low_column -= 1; } cout << endl; } // Driver code int main() { int mat[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int r = 3, c = 3; printSpiral(mat, r, c); }
constant
quadratic
// C++ program to print matrix in snake order #include <iostream> #define M 4 #define N 4 using namespace std; void print(int mat[M][N]) { // Traverse through all rows for (int i = 0; i < M; i++) { // If current row is even, print from // left to right if (i % 2 == 0) { for (int j = 0; j < N; j++) cout << mat[i][j] << " "; // If current row is odd, print from // right to left } else { for (int j = N - 1; j >= 0; j--) cout << mat[i][j] << " "; } } } // Driver code int main() { int mat[M][N] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 } }; print(mat); return 0; }
constant
quadratic
// C++ program to find the difference // between the sum of diagonal. #include <bits/stdc++.h> #define MAX 100 using namespace std; int difference(int arr[][MAX], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return abs(d1 - d2); } // Driven Program int main() { int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0; }
constant
quadratic
// C++ program to find the difference // between the sum of diagonal. #include <bits/stdc++.h> #define MAX 100 using namespace std; int difference(int arr[][MAX], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { // d1 store the sum of diagonal from // top-left to bottom-right d1 += arr[i][i]; // d2 store the sum of diagonal from // top-right to bottom-left d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return abs(d1 - d2); } // Driven Program int main() { int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0; }
constant
linear
// C++ program to construct ancestor matrix for // given tree. #include<bits/stdc++.h> using namespace std; #define MAX 100 /* A binary tree node */ struct Node { int data; Node *left, *right; }; // Creating a global boolean matrix for simplicity bool mat[MAX][MAX]; // anc[] stores all ancestors of current node. This // function fills ancestors for all nodes. // It also returns size of tree. Size of tree is // used to print ancestor matrix. int ancestorMatrixRec(Node *root, vector<int> &anc) { /* base case */ if (root == NULL) return 0;; // Update all ancestors of current node int data = root->data; for (int i=0; i<anc.size(); i++) mat[anc[i]][data] = true; // Push data to list of ancestors anc.push_back(data); // Traverse left and right subtrees int l = ancestorMatrixRec(root->left, anc); int r = ancestorMatrixRec(root->right, anc); // Remove data from list the list of ancestors // as all descendants of it are processed now. anc.pop_back(); return l+r+1; } // This function mainly calls ancestorMatrixRec() void ancestorMatrix(Node *root) { // Create an empty ancestor array vector<int> anc; // Fill ancestor matrix and find size of // tree. int n = ancestorMatrixRec(root, anc); // Print the filled values for (int i=0; i<n; i++) { for (int j=0; j<n; j++) cout << mat[i][j] << " "; cout << endl; } } /* Helper function to create a new node */ Node* newnode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } /* Driver program to test above functions*/ int main() { /* Construct the following binary tree 5 / \ 1 2 / \ / 0 4 3 */ Node *root = newnode(5); root->left = newnode(1); root->right = newnode(2); root->left->left = newnode(0); root->left->right = newnode(4); root->right->left = newnode(3); ancestorMatrix(root); return 0; }
quadratic
quadratic
// C++ program to construct ancestor matrix for // given tree. #include<bits/stdc++.h> using namespace std; #define size 6 int M[size][size]={0}; /* A binary tree node */ struct Node { int data; Node *left, *right; }; /* Helper function to create a new node */ Node* newnode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } void printMatrix(){ for(int i=0;i<size;i++){ for(int j=0;j<size;j++) cout<<M[i][j]<<" "; cout<<endl; } } //First PreOrder Traversal void MatrixUtil(Node *root,int index){ if(root==NULL)return; int preData=root->data; //Since there is no ancestor for root node, // so we doesn't assign it's value as 1 if(index==-1)index=root->data; else M[index][preData]=1; MatrixUtil(root->left,preData); MatrixUtil(root->right,preData); } void Matrix(Node *root){ // Call Func MatrixUtil MatrixUtil(root,-1); //Applying Transitive Closure for the given Matrix for(int i=0;i<size;i++){ for (int j = 0;j< size; j++) { for(int k=0;k<size;k++) M[j][k]=M[j][k]||(M[j][i]&&M[i][k]); } } //Printing Matrix printMatrix(); } /* Driver program to test above functions*/ int main() { Node *root = newnode(5); root->left = newnode(1); root->right = newnode(2); root->left->left = newnode(0); root->left->right = newnode(4); root->right->left = newnode(3); Matrix(root); return 0; }
quadratic
quadratic
// Given an ancestor matrix for binary tree, construct // the tree. #include <bits/stdc++.h> using namespace std; # define N 6 /* A binary tree node */ struct Node { int data; Node *left, *right; }; /* Helper function to create a new node */ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Constructs tree from ancestor matrix Node* ancestorTree(int mat[][N]) { // Binary array to determine whether // parent is set for node i or not int parent[N] = {0}; // Root will store the root of the constructed tree Node* root = NULL; // Create a multimap, sum is used as key and row // numbers are used as values multimap<int, int> mm; for (int i = 0; i < N; i++) { int sum = 0; // Initialize sum of this row for (int j = 0; j < N; j++) sum += mat[i][j]; // insert(sum, i) pairs into the multimap mm.insert(pair<int, int>(sum, i)); } // node[i] will store node for i in constructed tree Node* node[N]; // Traverse all entries of multimap. Note that values // are accessed in increasing order of sum for (auto it = mm.begin(); it != mm.end(); ++it) { // create a new node for every value node[it->second] = newNode(it->second); // To store last processed node. This node will be // root after loop terminates root = node[it->second]; // if non-leaf node if (it->first != 0) { // traverse row 'it->second' in the matrix for (int i = 0; i < N; i++) { // if parent is not set and ancestor exits if (!parent[i] && mat[it->second][i]) { // check for unoccupied left/right node // and set parent of node i if (!node[it->second]->left) node[it->second]->left = node[i]; else node[it->second]->right = node[i]; parent[i] = 1; } } } } return root; } /* Given a binary tree, print its nodes in inorder */ void printInorder(Node* node) { if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right); } // Driver code int main() { int mat[N][N] = {{ 0, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1, 0 }, { 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 1, 0 } }; Node* root = ancestorTree(mat); cout << "Inorder traversal of tree is \n"; // Function call printInorder(root); return 0; }
quadratic
quadratic
// C++ program to fill a matrix with values from // 1 to n*n in spiral fashion. #include <bits/stdc++.h> using namespace std; const int MAX = 100; // Fills a[m][n] with values from 1 to m*n in // spiral fashion. void spiralFill(int m, int n, int a[][MAX]) { // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) a[k][i] = val++; k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) a[i][n-1] = val++; n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) a[m-1][i] = val++; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) a[i][l] = val++; l++; } } } /* Driver program to test above functions */ int main() { int m = 4, n = 4; int a[MAX][MAX]; spiralFill(m, n, a); for (int i=0; i<m; i++) { for (int j=0; j<n; j++) cout << a[i][j] << " "; cout << endl; } return 0; }
quadratic
quadratic
/* C++ program for Sudoku generator */ #include <bits/stdc++.h> using namespace std; class Sudoku { public: int** mat; int N; // number of columns/rows. int SRN; // square root of N int K; // No. Of missing digits // Constructor Sudoku(int N, int K) { this->N = N; this->K = K; // Compute square root of N double SRNd = sqrt(N); SRN = (int)SRNd; mat = new int*[N]; // Create a row for every pointer for (int i = 0; i < N; i++) { // Note : Rows may not be contiguous mat[i] = new int[N]; // Initialize all entries as false to indicate // that there are no edges initially memset(mat[i], 0, N * sizeof(int)); } } // Sudoku Generator void fillValues() { // Fill the diagonal of SRN x SRN matrices fillDiagonal(); // Fill remaining blocks fillRemaining(0, SRN); // Remove Randomly K digits to make game removeKDigits(); } // Fill the diagonal SRN number of SRN x SRN matrices void fillDiagonal() { for (int i = 0; i < N; i = i + SRN) { // for diagonal box, start coordinates->i==j fillBox(i, i); } } // Returns false if given 3 x 3 block contains num. bool unUsedInBox(int rowStart, int colStart, int num) { for (int i = 0; i < SRN; i++) { for (int j = 0; j < SRN; j++) { if (mat[rowStart + i][colStart + j] == num) { return false; } } } return true; } // Fill a 3 x 3 matrix. void fillBox(int row, int col) { int num; for (int i = 0; i < SRN; i++) { for (int j = 0; j < SRN; j++) { do { num = randomGenerator(N); } while (!unUsedInBox(row, col, num)); mat[row + i][col + j] = num; } } } // Random generator int randomGenerator(int num) { return (int)floor( (float)(rand() / double(RAND_MAX) * num + 1)); } // Check if safe to put in cell bool CheckIfSafe(int i, int j, int num) { return ( unUsedInRow(i, num) && unUsedInCol(j, num) && unUsedInBox(i - i % SRN, j - j % SRN, num)); } // check in the row for existence bool unUsedInRow(int i, int num) { for (int j = 0; j < N; j++) { if (mat[i][j] == num) { return false; } } return true; } // check in the row for existence bool unUsedInCol(int j, int num) { for (int i = 0; i < N; i++) { if (mat[i][j] == num) { return false; } } return true; } // A recursive function to fill remaining // matrix bool fillRemaining(int i, int j) { // System.out.println(i+" "+j); if (j >= N && i < N - 1) { i = i + 1; j = 0; } if (i >= N && j >= N) { return true; } if (i < SRN) { if (j < SRN) { j = SRN; } } else if (i < N - SRN) { if (j == (int)(i / SRN) * SRN) { j = j + SRN; } } else { if (j == N - SRN) { i = i + 1; j = 0; if (i >= N) { return true; } } } for (int num = 1; num <= N; num++) { if (CheckIfSafe(i, j, num)) { mat[i][j] = num; if (fillRemaining(i, j + 1)) { return true; } mat[i][j] = 0; } } return false; } // Remove the K no. of digits to // complete game void removeKDigits() { int count = K; while (count != 0) { int cellId = randomGenerator(N * N) - 1; // System.out.println(cellId); // extract coordinates i and j int i = (cellId / N); int j = cellId % 9; if (j != 0) { j = j - 1; } // System.out.println(i+" "+j); if (mat[i][j] != 0) { count--; mat[i][j] = 0; } } } // Print sudoku void printSudoku() { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << to_string(mat[i][j]) + " "; } cout << endl; } cout << endl; } }; // Driver code int main() { int N = 9; int K = 20; Sudoku* sudoku = new Sudoku(N, K); sudoku->fillValues(); sudoku->printSudoku(); return 0; } // This code is contributed by Aarti_Rathi
quadratic
quadratic
#include <iostream> using namespace std; // change row and column value to set the canvas size const int row = 5; const int col = 4; // creates row boundary int row_line() { cout << endl; for (int i = 0; i < col; i++) { cout << " -----"; } cout << endl; } // returns the count of alive neighbours int count_live_neighbour_cell(int a[row][col], int r, int c) { int i, j, count = 0; for (i = r - 1; i <= r + 1; i++) { for (j = c - 1; j <= c + 1; j++) { if ((i == r && j == c) || (i < 0 || j < 0) || (i >= row || j >= col)) { continue; } if (a[i][j] == 1) { count++; } } } return count; } int main() { int a[row][col], b[row][col]; int i, j; int neighbour_live_cell; // generate matrix canvas with random values (live and // dead cells) for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { a[i][j] = rand() % 2; } } // print array matrix cout << "Initial Stage:"; row_line(); for (i = 0; i < row; i++) { cout << ":"; for (j = 0; j < col; j++) { cout << " " << a[i][j] << " :"; } row_line(); } // next canvas values based on live neighbour count for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { neighbour_live_cell = count_live_neighbour_cell(a, i, j); if (a[i][j] == 1 && (neighbour_live_cell == 2 || neighbour_live_cell == 3)) { b[i][j] = 1; } else if (a[i][j] == 0 && neighbour_live_cell == 3) { b[i][j] = 1; } else { b[i][j] = 0; } } } // print next generation cout << "\nNext Generation:"; row_line(); for (i = 0; i < row; i++) { cout << ":"; for (j = 0; j < col; j++) { cout << " " << b[i][j] << " :"; } row_line(); } return 0; } /* ###################################### OUTPUT #################################### Initial Stage: ----- ----- ----- ----- : 1 : 1 : 0 : 0 : ----- ----- ----- ----- : 1 : 0 : 0 : 0 : ----- ----- ----- ----- : 0 : 0 : 1 : 1 : ----- ----- ----- ----- : 1 : 1 : 1 : 1 : ----- ----- ----- ----- : 1 : 0 : 1 : 0 : ----- ----- ----- ----- Next Generation: ----- ----- ----- ----- : 1 : 1 : 0 : 0 : ----- ----- ----- ----- : 1 : 0 : 1 : 0 : ----- ----- ----- ----- : 1 : 0 : 0 : 1 : ----- ----- ----- ----- : 1 : 0 : 0 : 0 : ----- ----- ----- ----- : 1 : 0 : 1 : 1 : ----- ----- ----- ----- */ // This code is contributed by Tapesh(tapeshdua420)
quadratic
quadratic
// C++ program to find maximum sum of hour // glass in matrix #include<bits/stdc++.h> using namespace std; const int R = 5; const int C = 5; // Returns maximum sum of hour glass in ar[][] int findMaxSum(int mat[R][C]) { if (R<3 || C<3){ cout << "Not possible" << endl; exit(0); } // Here loop runs (R-2)*(C-2) times considering // different top left cells of hour glasses. int max_sum = INT_MIN; for (int i=0; i<R-2; i++) { for (int j=0; j<C-2; j++) { // Considering mat[i][j] as top left cell of // hour glass. int sum = (mat[i][j]+mat[i][j+1]+mat[i][j+2])+ (mat[i+1][j+1])+ (mat[i+2][j]+mat[i+2][j+1]+mat[i+2][j+2]); // If previous sum is less than current sum then // update new sum in max_sum max_sum = max(max_sum, sum); } } return max_sum; } // Driver code int main() { int mat[][C] = {{1, 2, 3, 0, 0}, {0, 0, 0, 0, 0}, {2, 1, 4, 0, 0}, {0, 0, 0, 0, 0}, {1, 1, 0, 1, 0}}; int res = findMaxSum(mat); cout << "Maximum sum of hour glass = "<< res << endl; return 0; } //Code is modified by Susobhan Akhuli
constant
quadratic
// C++ program for finding maximum and minimum in // a matrix. #include<bits/stdc++.h> using namespace std; #define MAX 100 // Finds maximum and minimum in arr[0..n-1][0..n-1] // using pair wise comparisons void maxMin(int arr[][MAX], int n) { int min = INT_MAX; int max = INT_MIN; // Traverses rows one by one for (int i = 0; i < n; i++) { for (int j = 0; j <= n/2; j++) { // Compare elements from beginning // and end of current row if (arr[i][j] > arr[i][n-j-1]) { if (min > arr[i][n-j-1]) min = arr[i][n-j-1]; if (max< arr[i][j]) max = arr[i][j]; } else { if (min > arr[i][j]) min = arr[i][j]; if (max< arr[i][n-j-1]) max = arr[i][n-j-1]; } } } cout << "Maximum = " << max << ", Minimum = " << min; } /* Driver program to test above function */ int main() { int arr[MAX][MAX] = {5, 9, 11, 25, 0, 14, 21, 6, 4}; maxMin(arr, 3); return 0; }
constant
quadratic
// C++ program to print matrix in anti-spiral form #include <bits/stdc++.h> using namespace std; #define R 4 #define C 5 void antiSpiralTraversal(int m, int n, int a[R][C]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ stack<int> stk; while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) stk.push(a[k][i]); k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) stk.push(a[i][n]); n--; /* Print the last row from the remaining rows */ if ( k <= m) { for (i = n; i >= l; --i) stk.push(a[m][i]); m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) stk.push(a[i][l]); l++; } } while (!stk.empty()) { cout << stk.top() << " "; stk.pop(); } } /* Driver program to test above functions */ int main() { int mat[R][C] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; antiSpiralTraversal(R-1, C-1, mat); return 0; }
quadratic
quadratic
// C++ program to find trace and normal // of given matrix #include<bits/stdc++.h> using namespace std; // Size of given matrix const int MAX = 100; // Returns Normal of a matrix of size n x n int findNormal(int mat[][MAX], int n) { int sum = 0; for (int i=0; i<n; i++) for (int j=0; j<n; j++) sum += mat[i][j]*mat[i][j]; return sqrt(sum); } // Returns trace of a matrix of size n x n int findTrace(int mat[][MAX], int n) { int sum = 0; for (int i=0; i<n; i++) sum += mat[i][i]; return sum; } // Driven source int main() { int mat[][MAX] = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; cout << "Trace of Matrix = " << findTrace(mat, 5) << endl; cout << "Normal of Matrix = " << findNormal(mat, 5) << endl; return 0; }
constant
quadratic
// C++ program to find minimum operations required // to set all the element of binary matrix #include <bits/stdc++.h> #define N 5 #define M 5 using namespace std; // Return minimum operation required to make all 1s. int minOperation(bool arr[N][M]) { int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = M - 1; j >= 0; j--) { // check if this cell equals 0 if(arr[i][j] == 0) { // increase the number of moves ans++; // flip from this cell to the start point for (int k = 0; k <= i; k++) { for (int h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == 1) arr[k][h] = 0; else arr[k][h] = 1; } } } } } return ans; } // Driven Program int main() { bool mat[N][M] = { 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; cout << minOperation(mat) << endl; return 0; }
quadratic
quadratic
// This is a modified code of // https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ #include <iostream> #define R 3 #define C 6 using namespace std; // Function that print matrix in reverse spiral form. void ReversespiralPrint(int m, int n, int a[R][C]) { // Large array to initialize it // with elements of matrix long int b[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m*n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { // printf("%d ", a[k][i]); val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { // printf("%d ", a[i][n-1]); val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { // printf("%d ", a[m-1][i]); val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { // printf("%d ", a[i][l]); val = a[i][l]; b[z] = val; ++z; } l++; } } for (int i=size-1 ; i>=0 ; --i) { cout<<b[i]<<" "; } } /* Driver program to test above functions */ int main() { int a[R][C] = { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; ReversespiralPrint(R, C, a); return 0; }
constant
quadratic
// C++ program to find sum of matrix element // where each element is integer division of // row and column. #include<bits/stdc++.h> using namespace std; // Return sum of matrix element where each element // is division of its corresponding row and column. int findSum(int n) { int ans = 0; for (int i = 1; i <= n; i++) // for rows for (int j = 1; j <= n; j++) // for columns ans += (i/j); return ans; } // Driven Program int main() { int N = 2; cout << findSum(N) << endl; return 0; }
constant
quadratic
// C++ program to find sum of matrix element // where each element is integer division of // row and column. #include<bits/stdc++.h> using namespace std; // Return sum of matrix element where each // element is division of its corresponding // row and column. int findSum(int n) { int ans = 0, temp = 0, num; // For each column. for (int i = 1; i <= n && temp < n; i++) { // count the number of elements of // each column. Initialize to i -1 // because number of zeroes are i - 1. temp = i - 1; // For multiply num = 1; while (temp < n) { if (temp + i <= n) ans += (i * num); else ans += ((n - temp) * num); temp += i; num ++; } } return ans; } // Driven Program int main() { int N = 2; cout << findSum(N) << endl; return 0; }
constant
quadratic
// C++ program to find // number of countOpsation // to make two matrix equals #include <bits/stdc++.h> using namespace std; const int MAX = 1000; int countOps(int A[][MAX], int B[][MAX], int m, int n) { // Update matrix A[][] // so that only A[][] // has to be countOpsed for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) A[i][j] -= B[i][j]; // Check necessary condition // for condition for // existence of full countOpsation for (int i = 1; i < n; i++) for (int j = 1; j < m; j++) if (A[i][j] - A[i][0] - A[0][j] + A[0][0] != 0) return -1; // If countOpsation is possible // calculate total countOpsation int result = 0; for (int i = 0; i < n; i++) result += abs(A[i][0]); for (int j = 0; j < m; j++) result += abs(A[0][j] - A[0][0]); return (result); } // Driver code int main() { int A[MAX][MAX] = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1}}; int B[MAX][MAX] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; cout << countOps(A, B, 3, 3) ; return 0; }
constant
quadratic
// C++ program to print 2 coils of a // 4n x 4n matrix. #include<iostream> using namespace std; // Print coils in a matrix of size 4n x 4n void printCoils(int n) { // Number of elements in each coil int m = 8*n*n; // Let us fill elements in coil 1. int coil1[m]; // First element of coil1 // 4*n*2*n + 2*n; coil1[0] = 8*n*n + 2*n; int curr = coil1[0]; int nflg = 1, step = 2; // Fill remaining m-1 elements in coil1[] int index = 1; while (index < m) { // Fill elements of current step from // down to up for (int i=0; i<step; i++) { // Next element from current element curr = coil1[index++] = (curr - 4*n*nflg); if (index >= m) break; } if (index >= m) break; // Fill elements of current step from // up to down. for (int i=0; i<step; i++) { curr = coil1[index++] = curr + nflg; if (index >= m) break; } nflg = nflg*(-1); step += 2; } /* get coil2 from coil1 */ int coil2[m]; for (int i=0; i<8*n*n; i++) coil2[i] = 16*n*n + 1 -coil1[i]; // Print both coils cout << "Coil 1 : "; for(int i=0; i<8*n*n; i++) cout << coil1[i] << " "; cout << "\nCoil 2 : "; for (int i=0; i<8*n*n; i++) cout << coil2[i] << " "; } // Driver code int main() { int n = 1; printCoils(n); return 0; }
quadratic
quadratic
// C++ program to find sum of matrix in which each // element is absolute difference of its corresponding // row and column number row. #include<bits/stdc++.h> using namespace std; // Return the sum of matrix in which each element // is absolute difference of its corresponding row // and column number row int findSum(int n) { // Generate matrix int arr[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) arr[i][j] = abs(i - j); // Compute sum int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += arr[i][j]; return sum; } // Driven Program int main() { int n = 3; cout << findSum(n) << endl; return 0; }
quadratic
quadratic