text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Find the closest element in Binary Search Tree | Recursive C ++ program to find key closest to k in given Binary Search Tree . ; A binary tree node has key , pointer to left child and a pointer to right child ; Utility that allocates a new node with the given key and NULL left and right pointers . ; Function to find node with minimum absolute difference with given K min_diff -- > minimum difference till now min_diff_key -- > node having minimum absolute difference with K ; If k itself is present ; update min_diff and min_diff_key by checking current node value ; if k is less than ptr -> key then move in left subtree else in right subtree ; Wrapper over maxDiffUtil ( ) ; Initialize minimum difference ; Find value of min_diff_key ( Closest key in tree with k ) ; Driver program to run the case | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; struct Node * newnode ( int key ) { struct Node * node = new ( struct Node ) ; node -> key = key ; node -> left = node -> right = NULL ; return ( node ) ; } void maxDiffUtil ( struct Node * ptr , int k , int & min_diff , int & min_diff_key ) { if ( ptr == NULL ) return ; if ( ptr -> key == k ) { min_diff_key = k ; return ; } if ( min_diff > abs ( ptr -> key - k ) ) { min_diff = abs ( ptr -> key - k ) ; min_diff_key = ptr -> key ; } if ( k < ptr -> key ) maxDiffUtil ( ptr -> left , k , min_diff , min_diff_key ) ; else maxDiffUtil ( ptr -> right , k , min_diff , min_diff_key ) ; } int maxDiff ( Node * root , int k ) { int min_diff = INT_MAX , min_diff_key = -1 ; maxDiffUtil ( root , k , min_diff , min_diff_key ) ; return min_diff_key ; } int main ( ) { struct Node * root = newnode ( 9 ) ; root -> left = newnode ( 4 ) ; root -> right = newnode ( 17 ) ; root -> left -> left = newnode ( 3 ) ; root -> left -> right = newnode ( 6 ) ; root -> left -> right -> left = newnode ( 5 ) ; root -> left -> right -> right = newnode ( 7 ) ; root -> right -> right = newnode ( 22 ) ; root -> right -> right -> left = newnode ( 20 ) ; int k = 18 ; cout << maxDiff ( root , k ) ; return 0 ; } |
Construct a complete binary tree from given array in level order fashion | CPP program to construct binary tree from given array in level order fashion Tree Node ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node ; Function to insert nodes in level order ; Base case for recursion ; insert left child ; insert right child ; Function to print tree nodes in InOrder fashion ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = ( Node * ) malloc ( sizeof ( Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } Node * insertLevelOrder ( int arr [ ] , Node * root , int i , int n ) { if ( i < n ) { Node * temp = newNode ( arr [ i ] ) ; root = temp ; root -> left = insertLevelOrder ( arr , root -> left , 2 * i + 1 , n ) ; root -> right = insertLevelOrder ( arr , root -> right , 2 * i + 2 , n ) ; } return root ; } void inOrder ( Node * root ) { if ( root != NULL ) { inOrder ( root -> left ) ; cout << root -> data << " β " ; inOrder ( root -> right ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 6 , 6 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Node * root = insertLevelOrder ( arr , root , 0 , n ) ; inOrder ( root ) ; } |
Construct Full Binary Tree from given preorder and postorder traversals | program for construction of full binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function to create a node ; A recursive function to construct Full from pre [ ] and post [ ] . preIndex is used to keep track of index in pre [ ] . l is low index and h is high index for the current subarray in post [ ] ; Base case ; The first node in preorder traversal is root . So take the node at preIndex from preorder and make it root , and increment preIndex ; If the current subarry has only one element , no need to recur ; Search the next element of pre [ ] in post [ ] ; Use the index of element found in postorder to divide postorder array in two parts . Left subtree and right subtree ; The main function to construct Full Binary Tree from given preorder and postorder traversals . This function mainly uses constructTreeUtil ( ) ; A utility function to print inorder traversal of a Binary Tree ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; node * newNode ( int data ) { node * temp = new node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } node * constructTreeUtil ( int pre [ ] , int post [ ] , int * preIndex , int l , int h , int size ) { if ( * preIndex >= size l > h ) return NULL ; node * root = newNode ( pre [ * preIndex ] ) ; ++ * preIndex ; if ( l == h ) return root ; int i ; for ( i = l ; i <= h ; ++ i ) if ( pre [ * preIndex ] == post [ i ] ) break ; if ( i <= h ) { root -> left = constructTreeUtil ( pre , post , preIndex , l , i , size ) ; root -> right = constructTreeUtil ( pre , post , preIndex , i + 1 , h , size ) ; } return root ; } node * constructTree ( int pre [ ] , int post [ ] , int size ) { int preIndex = 0 ; return constructTreeUtil ( pre , post , & preIndex , 0 , size - 1 , size ) ; } void printInorder ( node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> data << " β " ; printInorder ( node -> right ) ; } int main ( ) { int pre [ ] = { 1 , 2 , 4 , 8 , 9 , 5 , 3 , 6 , 7 } ; int post [ ] = { 8 , 9 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int size = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; node * root = constructTree ( pre , post , size ) ; cout << " Inorder β traversal β of β the β constructed β tree : β STRNEWLINE " ; printInorder ( root ) ; return 0 ; } |
Convert a Binary Tree to Threaded binary tree | Set 2 ( Efficient ) | C ++ program to convert a Binary Tree to Threaded Tree ; Structure of a node in threaded binary tree ; Used to indicate whether the right pointer is a normal right pointer or a pointer to inorder successor . ; Converts tree with given root to threaded binary tree . This function returns rightmost child of root . ; Base cases : Tree is empty or has single node ; Find predecessor if it exists ; Find predecessor of root ( Rightmost child in left subtree ) ; Link a thread from predecessor to root . ; If current node is rightmost child ; Recur for right subtree . ; A utility function to find leftmost node in a binary tree rooted with ' root ' . This function is used in inOrder ( ) ; Function to do inorder traversal of a threadded binary tree ; Find the leftmost node in Binary Tree ; If this Node is a thread Node , then go to inorder successor ; Else go to the leftmost child in right subtree ; A utility function to create a new node ; Driver program to test above functions ; 1 / \ 2 3 / \ / \ 4 5 6 7 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; bool isThreaded ; } ; Node * createThreaded ( Node * root ) { if ( root == NULL ) return NULL ; if ( root -> left == NULL && root -> right == NULL ) return root ; if ( root -> left != NULL ) { Node * l = createThreaded ( root -> left ) ; l -> right = root ; l -> isThreaded = true ; } if ( root -> right == NULL ) return root ; return createThreaded ( root -> right ) ; } Node * leftMost ( Node * root ) { while ( root != NULL && root -> left != NULL ) root = root -> left ; return root ; } void inOrder ( Node * root ) { if ( root == NULL ) return ; Node * cur = leftMost ( root ) ; while ( cur != NULL ) { cout << cur -> key << " β " ; if ( cur -> isThreaded ) cur = cur -> right ; else cur = leftMost ( cur -> right ) ; } } Node * newNode ( int key ) { Node * temp = new Node ; temp -> left = temp -> right = NULL ; temp -> key = key ; return temp ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; createThreaded ( root ) ; cout << " Inorder β traversal β of β created β " " threaded β tree β is STRNEWLINE " ; inOrder ( root ) ; return 0 ; } |
Inorder Non | C ++ program to print inorder traversal of a Binary Search Tree ( BST ) without recursion and stack ; BST Node ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Function to print inorder traversal using parent pointer ; Start traversal from root ; If left child is not traversed , find the leftmost child ; Print root 's data ; Mark left as done ; If right child exists ; If right child doesn 't exist, move to parent ; If this node is right child of its parent , visit parent 's parent first ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { Node * left , * right , * parent ; int key ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> parent = temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) { node -> left = insert ( node -> left , key ) ; node -> left -> parent = node ; } else if ( key > node -> key ) { node -> right = insert ( node -> right , key ) ; node -> right -> parent = node ; } return node ; } void inorder ( Node * root ) { bool leftdone = false ; while ( root ) { if ( ! leftdone ) { while ( root -> left ) root = root -> left ; } printf ( " % d β " , root -> key ) ; leftdone = true ; if ( root -> right ) { leftdone = false ; root = root -> right ; } else if ( root -> parent ) { while ( root -> parent && root == root -> parent -> right ) root = root -> parent ; if ( ! root -> parent ) break ; root = root -> parent ; } else break ; } } int main ( void ) { Node * root = NULL ; root = insert ( root , 24 ) ; root = insert ( root , 27 ) ; root = insert ( root , 29 ) ; root = insert ( root , 34 ) ; root = insert ( root , 14 ) ; root = insert ( root , 4 ) ; root = insert ( root , 10 ) ; root = insert ( root , 22 ) ; root = insert ( root , 13 ) ; root = insert ( root , 3 ) ; root = insert ( root , 2 ) ; root = insert ( root , 6 ) ; printf ( " Inorder β traversal β is β STRNEWLINE " ) ; inorder ( root ) ; return 0 ; } |
Sorted order printing of a given array that represents a BST | C ++ Code for Sorted order printing of a given array that represents a BST ; print left subtree ; print root ; print right subtree ; driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSorted ( int arr [ ] , int start , int end ) { if ( start > end ) return ; printSorted ( arr , start * 2 + 1 , end ) ; cout << arr [ start ] << " β " ; printSorted ( arr , start * 2 + 2 , end ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 5 , 1 , 3 } ; int arr_size = sizeof ( arr ) / sizeof ( int ) ; printSorted ( arr , 0 , arr_size - 1 ) ; getchar ( ) ; return 0 ; } |
Floor and Ceil from a BST | Program to find ceil of a given value in BST ; A binary tree node has key , left child and right child ; Helper function that allocates a new node with the given key and NULL left and right pointers . ; Function to find ceil of a given input in BST . If input is more than the max key in BST , return - 1 ; Base case ; We found equal key ; If root 's key is smaller, ceil must be in right subtree ; Else , either left subtree or root has the ceil value ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int key ; node * left ; node * right ; } ; node * newNode ( int key ) { node * Node = new node ( ) ; Node -> key = key ; Node -> left = NULL ; Node -> right = NULL ; return ( Node ) ; } int Ceil ( node * root , int input ) { if ( root == NULL ) return -1 ; if ( root -> key == input ) return root -> key ; if ( root -> key < input ) return Ceil ( root -> right , input ) ; int ceil = Ceil ( root -> left , input ) ; return ( ceil >= input ) ? ceil : root -> key ; } int main ( ) { node * root = newNode ( 8 ) ; root -> left = newNode ( 4 ) ; root -> right = newNode ( 12 ) ; root -> left -> left = newNode ( 2 ) ; root -> left -> right = newNode ( 6 ) ; root -> right -> left = newNode ( 10 ) ; root -> right -> right = newNode ( 14 ) ; for ( int i = 0 ; i < 16 ; i ++ ) cout << i << " β " << Ceil ( root , i ) << endl ; return 0 ; } |
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree | C ++ program to construct full binary tree using its preorder traversal and preorder traversal of its mirror tree ; A Binary Tree Node ; Utility function to create a new tree node ; A utility function to print inorder traversal of a Binary Tree ; A recursive function to construct Full binary tree from pre [ ] and preM [ ] . preIndex is used to keep track of index in pre [ ] . l is low index and h is high index for the current subarray in preM [ ] ; Base case ; The first node in preorder traversal is root . So take the node at preIndex from preorder and make it root , and increment preIndex ; If the current subarry has only one element , no need to recur ; Search the next element of pre [ ] in preM [ ] ; construct left and right subtrees recursively ; return root ; function to construct full binary tree using its preorder traversal and preorder traversal of its mirror tree ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void printInorder ( Node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d β " , node -> data ) ; printInorder ( node -> right ) ; } Node * constructBinaryTreeUtil ( int pre [ ] , int preM [ ] , int & preIndex , int l , int h , int size ) { if ( preIndex >= size l > h ) return NULL ; Node * root = newNode ( pre [ preIndex ] ) ; ++ ( preIndex ) ; if ( l == h ) return root ; int i ; for ( i = l ; i <= h ; ++ i ) if ( pre [ preIndex ] == preM [ i ] ) break ; if ( i <= h ) { root -> left = constructBinaryTreeUtil ( pre , preM , preIndex , i , h , size ) ; root -> right = constructBinaryTreeUtil ( pre , preM , preIndex , l + 1 , i - 1 , size ) ; } return root ; } void constructBinaryTree ( Node * root , int pre [ ] , int preMirror [ ] , int size ) { int preIndex = 0 ; int preMIndex = 0 ; root = constructBinaryTreeUtil ( pre , preMirror , preIndex , 0 , size - 1 , size ) ; printInorder ( root ) ; } int main ( ) { int preOrder [ ] = { 1 , 2 , 4 , 5 , 3 , 6 , 7 } ; int preOrderMirror [ ] = { 1 , 3 , 7 , 6 , 2 , 5 , 4 } ; int size = sizeof ( preOrder ) / sizeof ( preOrder [ 0 ] ) ; Node * root = new Node ; constructBinaryTree ( root , preOrder , preOrderMirror , size ) ; return 0 ; } |
Floor and Ceil from a BST | C ++ program to find floor and ceil of a given key in BST ; A binary tree node has key , left child and right child ; Helper function to find floor and ceil of a given key in BST ; Display the floor and ceil of a given key in BST . If key is less than the min key in BST , floor will be - 1 ; If key is more than the max key in BST , ceil will be - 1 ; ; Variables ' floor ' and ' ceil ' are passed by reference ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; Node ( int value ) { data = value ; left = right = NULL ; } } ; void floorCeilBSTHelper ( Node * root , int key , int & floor , int & ceil ) { while ( root ) { if ( root -> data == key ) { ceil = root -> data ; floor = root -> data ; return ; } if ( key > root -> data ) { floor = root -> data ; root = root -> right ; } else { ceil = root -> data ; root = root -> left ; } } return ; } void floorCeilBST ( Node * root , int key ) { int floor = -1 , ceil = -1 ; floorCeilBSTHelper ( root , key , floor , ceil ) ; cout << key << ' β ' << floor << ' β ' << ceil << ' ' ; } int main ( ) { Node * root = new Node ( 8 ) ; root -> left = new Node ( 4 ) ; root -> right = new Node ( 12 ) ; root -> left -> left = new Node ( 2 ) ; root -> left -> right = new Node ( 6 ) ; root -> right -> left = new Node ( 10 ) ; root -> right -> right = new Node ( 14 ) ; for ( int i = 0 ; i < 16 ; i ++ ) floorCeilBST ( root , i ) ; return 0 ; } |
How to handle duplicates in Binary Search Tree ? | C ++ program to implement basic operations ( search , insert and delete ) on a BST that handles duplicates by storing count with every node ; A utility function to create a new BST node ; A utility function to do inorder traversal of BST ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; If key already exists in BST , increment count and return ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the node with minimum key value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; Given a binary search tree and a key , this function deletes a given key and returns root of modified tree ; base case ; If the key to be deleted is smaller than the root 's key, then it lies in left subtree ; If the key to be deleted is greater than the root 's key, then it lies in right subtree ; if key is same as root 's key ; If key is present more than once , simply decrement count and return ; ElSE , delete the node node with only one child or no child ; node with two children : Get the inorder successor ( smallest in the right subtree ) ; Copy the inorder successor 's content to this node ; Delete the inorder successor ; Driver Code ; Let us create following BST 12 ( 3 ) / \ 10 ( 2 ) 20 ( 1 ) / \ 9 ( 1 ) 11 ( 1 ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int key ; int count ; struct node * left , * right ; } ; struct node * newNode ( int item ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> key = item ; temp -> left = temp -> right = NULL ; temp -> count = 1 ; return temp ; } void inorder ( struct node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; cout << root -> key << " ( " << root -> count << " ) β " ; inorder ( root -> right ) ; } } struct node * insert ( struct node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key == node -> key ) { ( node -> count ) ++ ; return node ; } if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else node -> right = insert ( node -> right , key ) ; return node ; } struct node * minValueNode ( struct node * node ) { struct node * current = node ; while ( current -> left != NULL ) current = current -> left ; return current ; } struct node * deleteNode ( struct node * root , int key ) { if ( root == NULL ) return root ; if ( key < root -> key ) root -> left = deleteNode ( root -> left , key ) ; else if ( key > root -> key ) root -> right = deleteNode ( root -> right , key ) ; else { if ( root -> count > 1 ) { ( root -> count ) -- ; return root ; } if ( root -> left == NULL ) { struct node * temp = root -> right ; free ( root ) ; return temp ; } else if ( root -> right == NULL ) { struct node * temp = root -> left ; free ( root ) ; return temp ; } struct node * temp = minValueNode ( root -> right ) ; root -> key = temp -> key ; root -> right = deleteNode ( root -> right , temp -> key ) ; } return root ; } int main ( ) { struct node * root = NULL ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 20 ) ; root = insert ( root , 9 ) ; root = insert ( root , 11 ) ; root = insert ( root , 10 ) ; root = insert ( root , 12 ) ; root = insert ( root , 12 ) ; cout << " Inorder β traversal β of β the β given β tree β " << endl ; inorder ( root ) ; cout << " Delete 20 " root = deleteNode ( root , 20 ) ; cout << " Inorder β traversal β of β the β modified β tree β STRNEWLINE " ; inorder ( root ) ; cout << " Delete 12 " root = deleteNode ( root , 12 ) ; cout << " Inorder β traversal β of β the β modified β tree β STRNEWLINE " ; inorder ( root ) ; cout << " Delete 9 " root = deleteNode ( root , 9 ) ; cout << " Inorder β traversal β of β the β modified β tree β STRNEWLINE " ; inorder ( root ) ; return 0 ; } |
How to implement decrease key or change key in Binary Search Tree ? | C ++ program to demonstrate decrease key operation on binary search tree ; A utility function to create a new BST node ; A utility function to do inorder traversal of BST ; A utility function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; Given a non - empty binary search tree , return the node with minimum key value found in that tree . Note that the entire tree does not need to be searched . ; loop down to find the leftmost leaf ; Given a binary search tree and a key , this function deletes the key and returns the new root ; base case ; If the key to be deleted is smaller than the root 's key, then it lies in left subtree ; If the key to be deleted is greater than the root 's key, then it lies in right subtree ; if key is same as root 's key, then This is the node to be deleted ; node with only one child or no child ; node with two children : Get the inorder successor ( smallest in the right subtree ) ; Copy the inorder successor 's content to this node ; Delete the inorder successor ; Function to decrease a key value in Binary Search Tree ; First delete old key value ; Then insert new key value ; Return new root ; Driver code ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 ; BST is modified to 50 / \ 30 70 / / \ 20 60 80 / 10 | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int key ; node * left , * right ; } ; node * newNode ( int item ) { node * temp = new node ; temp -> key = item ; temp -> left = temp -> right = NULL ; return temp ; } void inorder ( node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; cout << root -> key << " β " ; inorder ( root -> right ) ; } } node * insert ( node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else node -> right = insert ( node -> right , key ) ; return node ; } node * minValueNode ( node * Node ) { node * current = Node ; while ( current -> left != NULL ) current = current -> left ; return current ; } node * deleteNode ( node * root , int key ) { if ( root == NULL ) return root ; if ( key < root -> key ) root -> left = deleteNode ( root -> left , key ) ; else if ( key > root -> key ) root -> right = deleteNode ( root -> right , key ) ; else { if ( root -> left == NULL ) { node * temp = root -> right ; free ( root ) ; return temp ; } else if ( root -> right == NULL ) { node * temp = root -> left ; free ( root ) ; return temp ; } node * temp = minValueNode ( root -> right ) ; root -> key = temp -> key ; root -> right = deleteNode ( root -> right , temp -> key ) ; } return root ; } node * changeKey ( node * root , int oldVal , int newVal ) { root = deleteNode ( root , oldVal ) ; root = insert ( root , newVal ) ; return root ; } int main ( ) { node * root = NULL ; root = insert ( root , 50 ) ; root = insert ( root , 30 ) ; root = insert ( root , 20 ) ; root = insert ( root , 40 ) ; root = insert ( root , 70 ) ; root = insert ( root , 60 ) ; root = insert ( root , 80 ) ; cout << " Inorder β traversal β of β the β given β tree β STRNEWLINE " ; inorder ( root ) ; root = changeKey ( root , 40 , 10 ) ; cout << " Inorder traversal of the modified tree " ; inorder ( root ) ; return 0 ; } |
Print Common Nodes in Two Binary Search Trees | C ++ program of iterative traversal based method to find common elements in two BSTs . ; A BST node ; A utility function to create a new node ; Function two print common elements in given two trees ; Create two stacks for two inorder traversals ; push the Nodes of first tree in stack s1 ; push the Nodes of second tree in stack s2 ; Both root1 and root2 are NULL here ; If current keys in two trees are same ; move to the inorder successor ; If Node of first tree is smaller , than that of second tree , then its obvious that the inorder successors of current Node can have same value as that of the second tree Node . Thus , we pop from s2 ; root2 is set to NULL , because we need new Nodes of tree 1 ; Both roots and both stacks are empty ; A utility function to do inorder traversal ; A utility function to insert a new Node with given key in BST ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; return the ( unchanged ) Node pointer ; Driver program ; Create first tree as shown in example ; Create second tree as shown in example | #include <iostream> NEW_LINE #include <stack> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int ele ) { Node * temp = new Node ; temp -> key = ele ; temp -> left = temp -> right = NULL ; return temp ; } void printCommon ( Node * root1 , Node * root2 ) { stack < Node * > stack1 , s1 , s2 ; while ( 1 ) { if ( root1 ) { s1 . push ( root1 ) ; root1 = root1 -> left ; } else if ( root2 ) { s2 . push ( root2 ) ; root2 = root2 -> left ; } else if ( ! s1 . empty ( ) && ! s2 . empty ( ) ) { root1 = s1 . top ( ) ; root2 = s2 . top ( ) ; if ( root1 -> key == root2 -> key ) { cout << root1 -> key << " β " ; s1 . pop ( ) ; s2 . pop ( ) ; root1 = root1 -> right ; root2 = root2 -> right ; } else if ( root1 -> key < root2 -> key ) { s1 . pop ( ) ; root1 = root1 -> right ; root2 = NULL ; } else if ( root1 -> key > root2 -> key ) { s2 . pop ( ) ; root2 = root2 -> right ; root1 = NULL ; } } else break ; } } void inorder ( struct Node * root ) { if ( root ) { inorder ( root -> left ) ; cout << root -> key << " β " ; inorder ( root -> right ) ; } } struct Node * insert ( struct Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key ) ; else if ( key > node -> key ) node -> right = insert ( node -> right , key ) ; return node ; } int main ( ) { Node * root1 = NULL ; root1 = insert ( root1 , 5 ) ; root1 = insert ( root1 , 1 ) ; root1 = insert ( root1 , 10 ) ; root1 = insert ( root1 , 0 ) ; root1 = insert ( root1 , 4 ) ; root1 = insert ( root1 , 7 ) ; root1 = insert ( root1 , 9 ) ; Node * root2 = NULL ; root2 = insert ( root2 , 10 ) ; root2 = insert ( root2 , 7 ) ; root2 = insert ( root2 , 20 ) ; root2 = insert ( root2 , 4 ) ; root2 = insert ( root2 , 9 ) ; cout << " Tree β 1 β : β " ; inorder ( root1 ) ; cout << endl ; cout << " Tree β 2 β : β " ; inorder ( root2 ) ; cout << " Common Nodes : " printCommon ( root1 , root2 ) ; return 0 ; } |
Leaf nodes from Preorder of a Binary Search Tree | C ++ program to print leaf node from preorder of binary search tree . ; Binary Search ; Point to the index in preorder . ; Function to print Leaf Nodes by doing preorder traversal of tree using preorder and inorder arrays . ; If l == r , therefore no right or left subtree . So , it must be leaf Node , print it . ; If array is out of bound , return . ; Finding the index of preorder element in inorder array using binary search . ; Incrementing the index . ; Finding on the left subtree . ; Finding on the right subtree . ; Finds leaf nodes from given preorder traversal . ; To store inorder traversal ; Copy the preorder into another array . ; Finding the inorder by sorting the array . ; Print the Leaf Nodes . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( int inorder [ ] , int l , int r , int d ) { int mid = ( l + r ) >> 1 ; if ( inorder [ mid ] == d ) return mid ; else if ( inorder [ mid ] > d ) return binarySearch ( inorder , l , mid - 1 , d ) ; else return binarySearch ( inorder , mid + 1 , r , d ) ; } int ind = 0 ; void leafNodesRec ( int preorder [ ] , int inorder [ ] , int l , int r , int * ind , int n ) { if ( l == r ) { printf ( " % d β " , inorder [ l ] ) ; * ind = * ind + 1 ; return ; } if ( l < 0 l > r r >= n ) return ; int loc = binarySearch ( inorder , l , r , preorder [ * ind ] ) ; * ind = * ind + 1 ; leafNodesRec ( preorder , inorder , l , loc - 1 , ind , n ) ; leafNodesRec ( preorder , inorder , loc + 1 , r , ind , n ) ; } void leafNodes ( int preorder [ ] , int n ) { int inorder [ n ] ; for ( int i = 0 ; i < n ; i ++ ) inorder [ i ] = preorder [ i ] ; sort ( inorder , inorder + n ) ; leafNodesRec ( preorder , inorder , 0 , n - 1 , & ind , n ) ; } int main ( ) { int preorder [ ] = { 890 , 325 , 290 , 530 , 965 } ; int n = sizeof ( preorder ) / sizeof ( preorder [ 0 ] ) ; leafNodes ( preorder , n ) ; return 0 ; } |
Leaf nodes from Preorder of a Binary Search Tree | Stack based C ++ program to print leaf nodes from preorder traversal . ; Print the leaf node from the given preorder of BST . ; Since rightmost element is always leaf node . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void leafNode ( int preorder [ ] , int n ) { stack < int > s ; for ( int i = 0 , j = 1 ; j < n ; i ++ , j ++ ) { bool found = false ; if ( preorder [ i ] > preorder [ j ] ) s . push ( preorder [ i ] ) ; else { while ( ! s . empty ( ) ) { if ( preorder [ j ] > s . top ( ) ) { s . pop ( ) ; found = true ; } else break ; } } if ( found ) cout << preorder [ i ] << " β " ; } cout << preorder [ n - 1 ] ; } int main ( ) { int preorder [ ] = { 890 , 325 , 290 , 530 , 965 } ; int n = sizeof ( preorder ) / sizeof ( preorder [ 0 ] ) ; leafNode ( preorder , n ) ; return 0 ; } |
Leaf nodes from Preorder of a Binary Search Tree ( Using Recursion ) | Recursive C ++ program to find leaf nodes from given preorder traversal ; Print the leaf node from the given preorder of BST . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isLeaf ( int pre [ ] , int & i , int n , int min , int max ) { if ( i >= n ) return false ; if ( pre [ i ] > min && pre [ i ] < max ) { i ++ ; bool left = isLeaf ( pre , i , n , min , pre [ i - 1 ] ) ; bool right = isLeaf ( pre , i , n , pre [ i - 1 ] , max ) ; if ( ! left && ! right ) cout << pre [ i - 1 ] << " β " ; return true ; } return false ; } void printLeaves ( int preorder [ ] , int n ) { int i = 0 ; isLeaf ( preorder , i , n , INT_MIN , INT_MAX ) ; } int main ( ) { int preorder [ ] = { 890 , 325 , 290 , 530 , 965 } ; int n = sizeof ( preorder ) / sizeof ( preorder [ 0 ] ) ; printLeaves ( preorder , n ) ; return 0 ; } |
Binary Search Tree insert with Parent Pointer | C ++ program to demonstrate insert operation in binary search tree with parent pointer ; Node structure ; A utility function to create a new BST Node ; A utility function to do inorder traversal of BST ; A utility function to insert a new Node with given key in BST ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; Set parent of root of left subtree ; Set parent of root of right subtree ; return the ( unchanged ) Node pointer ; Driver Program to test above functions ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 ; print iNoder traversal of the BST | #include <bits/stdc++.h> NEW_LINE struct Node { int key ; struct Node * left , * right , * parent ; } ; struct Node * newNode ( int item ) { struct Node * temp = new Node ; temp -> key = item ; temp -> left = temp -> right = NULL ; temp -> parent = NULL ; return temp ; } void inorder ( struct Node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; printf ( " Node β : β % d , β " , root -> key ) ; if ( root -> parent == NULL ) printf ( " Parent β : β NULL β STRNEWLINE " ) ; else printf ( " Parent β : β % d β STRNEWLINE " , root -> parent -> key ) ; inorder ( root -> right ) ; } } struct Node * insert ( struct Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) { Node * lchild = insert ( node -> left , key ) ; node -> left = lchild ; lchild -> parent = node ; } else if ( key > node -> key ) { Node * rchild = insert ( node -> right , key ) ; node -> right = rchild ; rchild -> parent = node ; } return node ; } int main ( ) { struct Node * root = NULL ; root = insert ( root , 50 ) ; insert ( root , 30 ) ; insert ( root , 20 ) ; insert ( root , 40 ) ; insert ( root , 70 ) ; insert ( root , 60 ) ; insert ( root , 80 ) ; inorder ( root ) ; return 0 ; } |
Construct a special tree from given preorder traversal | A program to construct Binary Tree from preorder traversal ; A binary tree node structure ; Utility function to create a new Binary Tree node ; A recursive function to create a Binary Tree from given pre [ ] preLN [ ] arrays . The function returns root of tree . index_ptr is used to update index values in recursive calls . index must be initially passed as 0 ; store the current value of index in pre [ ] ; Base Case : All nodes are constructed ; Allocate memory for this node and increment index for subsequent recursive calls ; If this is an internal node , construct left and right subtrees and link the subtrees ; A wrapper over constructTreeUtil ( ) ; Initialize index as 0. Value of index is used in recursion to maintain the current index in pre [ ] and preLN [ ] arrays . ; This function is used only for testing ; first recur on left child ; then print the data of node ; now recur on right child ; Driver function to test above functions | #include <bits/stdc++.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; struct node * newNode ( int data ) { struct node * temp = new struct node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } struct node * constructTreeUtil ( int pre [ ] , char preLN [ ] , int * index_ptr , int n ) { int index = * index_ptr ; if ( index == n ) return NULL ; struct node * temp = newNode ( pre [ index ] ) ; ( * index_ptr ) ++ ; if ( preLN [ index ] == ' N ' ) { temp -> left = constructTreeUtil ( pre , preLN , index_ptr , n ) ; temp -> right = constructTreeUtil ( pre , preLN , index_ptr , n ) ; } return temp ; } struct node * constructTree ( int pre [ ] , char preLN [ ] , int n ) { int index = 0 ; return constructTreeUtil ( pre , preLN , & index , n ) ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d β " , node -> data ) ; printInorder ( node -> right ) ; } int main ( ) { struct node * root = NULL ; int pre [ ] = { 10 , 30 , 20 , 5 , 15 } ; char preLN [ ] = { ' N ' , ' N ' , ' L ' , ' L ' , ' L ' } ; int n = sizeof ( pre ) / sizeof ( pre [ 0 ] ) ; root = constructTree ( pre , preLN , n ) ; printf ( " Following β is β Inorder β Traversal β of β the β Constructed β Binary β Tree : β STRNEWLINE " ) ; printInorder ( root ) ; return 0 ; } |
Minimum Possible value of | ai + aj | CPP program to find number of pairs and minimal possible value ; function for finding pairs and min value ; initialize smallest and count ; iterate over all pairs ; is abs value is smaller than smallest update smallest and reset count to 1 ; if abs value is equal to smallest increment count value ; print result ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void pairs ( int arr [ ] , int n , int k ) { int smallest = INT_MAX ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) { if ( abs ( arr [ i ] + arr [ j ] - k ) < smallest ) { smallest = abs ( arr [ i ] + arr [ j ] - k ) ; count = 1 ; } else if ( abs ( arr [ i ] + arr [ j ] - k ) == smallest ) count ++ ; } cout << " Minimal β Value β = β " << smallest << " STRNEWLINE " ; cout << " Total β Pairs β = β " << count << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 , 5 , 1 , 9 , 9 } ; int k = 12 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pairs ( arr , n , k ) ; return 0 ; } |
Rank of an element in a stream | CPP program to find rank of an element in a stream . ; Inserting a new Node . ; Updating size of left subtree . ; Function to get Rank of a Node x . ; Step 1. ; Step 2. ; Step 3. ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; int leftSize ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; temp -> leftSize = 0 ; return temp ; } Node * insert ( Node * & root , int data ) { if ( ! root ) return newNode ( data ) ; if ( data <= root -> data ) { root -> left = insert ( root -> left , data ) ; root -> leftSize ++ ; } else root -> right = insert ( root -> right , data ) ; return root ; } int getRank ( Node * root , int x ) { if ( root -> data == x ) return root -> leftSize ; if ( x < root -> data ) { if ( ! root -> left ) return -1 ; else return getRank ( root -> left , x ) ; } else { if ( ! root -> right ) return -1 ; else { int rightSize = getRank ( root -> right , x ) ; if ( rightSize == -1 ) return -1 ; return root -> leftSize + 1 + rightSize ; } } } int main ( ) { int arr [ ] = { 5 , 1 , 4 , 4 , 5 , 9 , 7 , 13 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 4 ; Node * root = NULL ; for ( int i = 0 ; i < n ; i ++ ) root = insert ( root , arr [ i ] ) ; cout << " Rank β of β " << x << " β in β stream β is : β " << getRank ( root , x ) << endl ; x = 13 ; cout << " Rank β of β " << x << " β in β stream β is : β " << getRank ( root , x ) << endl ; x = 8 ; cout << " Rank β of β " << x << " β in β stream β is : β " << getRank ( root , x ) << endl ; return 0 ; } |
Rank of an element in a stream | C ++ program to find rank of an element in a stream . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int a [ ] = { 5 , 1 , 14 , 4 , 15 , 9 , 7 , 20 , 11 } ; int key = 20 ; int arraySize = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int count = 0 ; for ( int i = 0 ; i < arraySize ; i ++ ) { if ( a [ i ] <= key ) { count += 1 ; } } cout << " Rank β of β " << key << " β in β stream β is : β " << count - 1 << endl ; return 0 ; } |
Construct Special Binary Tree from given Inorder traversal | C ++ program to construct tree from inorder traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Prototypes of a utility function to get the maximum value in inorder [ start . . end ] ; Recursive function to construct binary of size len from Inorder traversal inorder [ ] . Initial values of start and end should be 0 and len - 1. ; Find index of the maximum element from Binary Tree ; Pick the maximum value and make it root ; If this is the only element in inorder [ start . . end ] , then return it ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of the maximum value in arr [ start ... end ] ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; This funtcion is here just to test buildTree ( ) ; first recur on left child ; then print the data of node ; now recur on right child ; Driver code ; Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 ; Let us test the built tree by printing Insorder traversal | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; } ; int max ( int inorder [ ] , int strt , int end ) ; node * newNode ( int data ) ; node * buildTree ( int inorder [ ] , int start , int end ) { if ( start > end ) return NULL ; int i = max ( inorder , start , end ) ; node * root = newNode ( inorder [ i ] ) ; if ( start == end ) return root ; root -> left = buildTree ( inorder , start , i - 1 ) ; root -> right = buildTree ( inorder , i + 1 , end ) ; return root ; } int max ( int arr [ ] , int strt , int end ) { int i , max = arr [ strt ] , maxind = strt ; for ( i = strt + 1 ; i <= end ; i ++ ) { if ( arr [ i ] > max ) { max = arr [ i ] ; maxind = i ; } } return maxind ; } node * newNode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; return Node ; } void printInorder ( node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> data << " β " ; printInorder ( node -> right ) ; } int main ( ) { int inorder [ ] = { 5 , 10 , 40 , 30 , 28 } ; int len = sizeof ( inorder ) / sizeof ( inorder [ 0 ] ) ; node * root = buildTree ( inorder , 0 , len - 1 ) ; cout << " Inorder β traversal β of β the β constructed β tree β is β STRNEWLINE " ; printInorder ( root ) ; return 0 ; } |
Continuous Tree | C ++ program to check if a tree is continuous or not ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Function to check tree is continuous or not ; if next node is empty then return true ; if current node is leaf node then return true because it is end of root to leaf path ; If left subtree is empty , then only check right ; If right subtree is empty , then only check left ; If both left and right subtrees are not empty , check everything ; Driver program to test mirror ( ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } bool treeContinuous ( struct Node * ptr ) { if ( ptr == NULL ) return true ; if ( ptr -> left == NULL && ptr -> right == NULL ) return true ; if ( ptr -> left == NULL ) return ( abs ( ptr -> data - ptr -> right -> data ) == 1 ) && treeContinuous ( ptr -> right ) ; if ( ptr -> right == NULL ) return ( abs ( ptr -> data - ptr -> left -> data ) == 1 ) && treeContinuous ( ptr -> left ) ; return abs ( ptr -> data - ptr -> left -> data ) == 1 && abs ( ptr -> data - ptr -> right -> data ) == 1 && treeContinuous ( ptr -> left ) && treeContinuous ( ptr -> right ) ; } int main ( ) { struct Node * root = newNode ( 3 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 4 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> right = newNode ( 5 ) ; treeContinuous ( root ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Sum of middle row and column in Matrix | C ++ program to find sum of middle row and column in matrix ; loop for sum of row ; loop for sum of column ; Driver function | #include <iostream> NEW_LINE using namespace std ; const int MAX = 100 ; void middlesum ( int mat [ ] [ MAX ] , int n ) { int row_sum = 0 , col_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) row_sum += mat [ n / 2 ] [ i ] ; cout << " Sum β of β middle β row β = β " << row_sum << endl ; for ( int i = 0 ; i < n ; i ++ ) col_sum += mat [ i ] [ n / 2 ] ; cout << " Sum β of β middle β column β = β " << col_sum ; } int main ( ) { int mat [ ] [ MAX ] = { { 2 , 5 , 7 } , { 3 , 7 , 2 } , { 5 , 6 , 9 } } ; middlesum ( mat , 3 ) ; return 0 ; } |
Row | C program showing time difference in row major and column major access ; taking MAX 10000 so that time difference can be shown ; accessing element row wise ; accessing element column wise ; driver code ; Time taken by row major order ; Time taken by column major order | #include <stdio.h> NEW_LINE #include <time.h> NEW_LINE #define MAX 10000 NEW_LINE int arr [ MAX ] [ MAX ] = { 0 } ; void rowMajor ( ) { int i , j ; for ( i = 0 ; i < MAX ; i ++ ) { for ( j = 0 ; j < MAX ; j ++ ) { arr [ i ] [ j ] ++ ; } } } void colMajor ( ) { int i , j ; for ( i = 0 ; i < MAX ; i ++ ) { for ( j = 0 ; j < MAX ; j ++ ) { arr [ j ] [ i ] ++ ; } } } int main ( ) { int i , j ; clock_t t = clock ( ) ; rowMajor ( ) ; t = clock ( ) - t ; printf ( " Row β major β access β time β : % f β s STRNEWLINE " , t / ( float ) CLOCKS_PER_SEC ) ; t = clock ( ) ; colMajor ( ) ; t = clock ( ) - t ; printf ( " Column β major β access β time β : % f β s STRNEWLINE " , t / ( float ) CLOCKS_PER_SEC ) ; return 0 ; } |
Rotate the matrix right by K times | CPP program to rotate a matrix right by k times ; size of matrix ; function to rotate matrix by k times ; temporary array of size M ; within the size of matrix ; copy first M - k elements to temporary array ; copy the elements from k to end to starting ; copy elements from temporary array to end ; function to display the matrix ; Driver 's code ; rotate matrix by k ; display rotated matrix | #include <iostream> NEW_LINE #define M 3 NEW_LINE #define N 3 NEW_LINE using namespace std ; void rotateMatrix ( int matrix [ ] [ M ] , int k ) { int temp [ M ] ; k = k % M ; for ( int i = 0 ; i < N ; i ++ ) { for ( int t = 0 ; t < M - k ; t ++ ) temp [ t ] = matrix [ i ] [ t ] ; for ( int j = M - k ; j < M ; j ++ ) matrix [ i ] [ j - M + k ] = matrix [ i ] [ j ] ; for ( int j = k ; j < M ; j ++ ) matrix [ i ] [ j ] = temp [ j - k ] ; } } 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 ; } } int main ( ) { int matrix [ N ] [ M ] = { { 12 , 23 , 34 } , { 45 , 56 , 67 } , { 78 , 89 , 91 } } ; int k = 2 ; rotateMatrix ( matrix , k ) ; displayMatrix ( matrix ) ; return 0 ; } |
Program to check Involutory Matrix | Program to implement involutory matrix . ; Function for matrix multiplication . ; Function to check involutory matrix . ; multiply function call . ; Driver function . ; Function call . If function return true then if part will execute otherwise else part will execute . | #include <bits/stdc++.h> NEW_LINE #define N 3 NEW_LINE using namespace std ; 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 ] ; } } } bool InvolutoryMatrix ( int mat [ N ] [ N ] ) { int res [ N ] [ N ] ; 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 ; } int main ( ) { int mat [ N ] [ N ] = { { 1 , 0 , 0 } , { 0 , -1 , 0 } , { 0 , 0 , -1 } } ; if ( InvolutoryMatrix ( mat ) ) cout << " Involutory β Matrix " ; else cout << " Not β Involutory β Matrix " ; return 0 ; } |
Interchange elements of first and last rows in matrix | C ++ code to swap the element of first and last row and display the result ; swapping of element between first and last rows ; Driver function ; input in the array ; printing the interchanged matrix | #include <iostream> NEW_LINE using namespace std ; #define n 4 NEW_LINE void interchangeFirstLast ( int m [ ] [ n ] ) { int rows = n ; for ( int i = 0 ; i < n ; i ++ ) { int t = m [ 0 ] [ i ] ; m [ 0 ] [ i ] = m [ rows - 1 ] [ i ] ; m [ rows - 1 ] [ i ] = t ; } } int main ( ) { int m [ n ] [ n ] = { { 8 , 9 , 7 , 6 } , { 4 , 7 , 6 , 5 } , { 3 , 2 , 1 , 8 } , { 9 , 9 , 7 , 7 } } ; interchangeFirstLast ( m ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) cout << m [ i ] [ j ] << " β " ; cout << endl ; } } |
Construct Binary Tree from given Parent Array representation | C ++ program to construct a Binary Tree from parent array ; A tree node ; Utility function to create new Node ; Creates a node with key as ' i ' . If i is root , then it changes root . If parent of i is not created , then it creates parent first ; If this node is already created ; Create a new node and set created [ i ] ; If ' i ' is root , change root pointer and return ; If parent is not created , then create parent first ; Find parent pointer ; If this is first child of parent ; If second child ; Creates tree from parent [ 0. . n - 1 ] and returns root of the created tree ; Create an array created [ ] to keep track of created nodes , initialize all entries as NULL ; For adding new line in a program ; Utility function to do inorder traversal ; Driver method | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } void createNode ( int parent [ ] , int i , Node * created [ ] , Node * * root ) { if ( created [ i ] != NULL ) return ; created [ i ] = newNode ( i ) ; if ( parent [ i ] == -1 ) { * root = created [ i ] ; return ; } if ( created [ parent [ i ] ] == NULL ) createNode ( parent , parent [ i ] , created , root ) ; Node * p = created [ parent [ i ] ] ; if ( p -> left == NULL ) p -> left = created [ i ] ; else p -> right = created [ i ] ; } Node * createTree ( int parent [ ] , int n ) { Node * created [ n ] ; for ( int i = 0 ; i < n ; i ++ ) created [ i ] = NULL ; Node * root = NULL ; for ( int i = 0 ; i < n ; i ++ ) createNode ( parent , i , created , & root ) ; return root ; } inline void newLine ( ) { cout << " STRNEWLINE " ; } void inorder ( Node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; cout << root -> key << " β " ; inorder ( root -> right ) ; } } int main ( ) { int parent [ ] = { -1 , 0 , 0 , 1 , 1 , 3 , 5 } ; int n = sizeof parent / sizeof parent [ 0 ] ; Node * root = createTree ( parent , n ) ; cout << " Inorder β Traversal β of β constructed β tree STRNEWLINE " ; inorder ( root ) ; newLine ( ) ; } |
Row wise sorting in 2D array | C ++ code to sort 2D matrix row - wise ; loop for rows of matrix ; loop for column of matrix ; loop for comparison and swapping ; swapping of elements ; printing the sorted matrix ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sortRowWise ( int m [ ] [ 4 ] , int r , int c ) { for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { for ( int k = 0 ; k < c - j - 1 ; k ++ ) { if ( m [ i ] [ k ] > m [ i ] [ k + 1 ] ) { swap ( m [ i ] [ k ] , m [ i ] [ k + 1 ] ) ; } } } } for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) cout << m [ i ] [ j ] << " β " ; cout << endl ; } } int main ( ) { int m [ ] [ 4 ] = { { 9 , 8 , 7 , 1 } , { 7 , 3 , 0 , 2 } , { 9 , 5 , 3 , 2 } , { 6 , 3 , 1 , 2 } } ; int r = sizeof ( m [ 0 ] ) / sizeof ( m [ 0 ] [ 0 ] ) ; int c = sizeof ( m ) / sizeof ( m [ 0 ] ) ; sortRowWise ( m , r , c ) ; return 0 ; } |
Row wise sorting in 2D array | C ++ code to sort 2D matrix row - wise ; One by one sort individual rows . ; Printing the sorted matrix ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 4 NEW_LINE #define N 4 NEW_LINE int sortRowWise ( int m [ M ] [ N ] ) { for ( int i = 0 ; i < M ; i ++ ) sort ( m [ i ] , m [ i ] + N ) ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) cout << ( m [ i ] [ j ] ) << " β " ; cout << endl ; } } int main ( ) { int m [ M ] [ N ] = { { 9 , 8 , 7 , 1 } , { 7 , 3 , 0 , 2 } , { 9 , 5 , 3 , 2 } , { 6 , 3 , 1 , 2 } } ; sortRowWise ( m ) ; } |
Program for Markov matrix | C ++ code to check Markov Matrix ; outer loop to access rows and inner to access columns ; Find sum of current row ; Driver Code ; Matrix to check ; calls the function check ( ) | #include <iostream> NEW_LINE using namespace std ; #define n 3 NEW_LINE bool checkMarkov ( double m [ ] [ n ] ) { for ( int i = 0 ; i < n ; i ++ ) { double sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) sum = sum + m [ i ] [ j ] ; if ( sum != 1 ) return false ; } return true ; } int main ( ) { double m [ 3 ] [ 3 ] = { { 0 , 0 , 1 } , { 0.5 , 0 , 0.5 } , { 1 , 0 , 0 } } ; if ( checkMarkov ( m ) ) cout << " β yes β " ; else cout << " β no β " ; } |
Program to check diagonal matrix and scalar matrix | Program to check matrix is diagonal matrix or not . ; Function to check matrix is diagonal matrix or not . ; condition to check other elements except main diagonal are zero or not . ; Driver function | #include <bits/stdc++.h> NEW_LINE #define N 4 NEW_LINE using namespace std ; bool isDiagonalMatrix ( int mat [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) if ( ( i != j ) && ( mat [ i ] [ j ] != 0 ) ) return false ; return true ; } 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 ; } |
Program to check diagonal matrix and scalar matrix | Program to check matrix is scalar matrix or not . ; Function to check matrix is scalar matrix or not . ; Check all elements except main diagonal are zero or not . ; Check all diagonal elements are same or not . ; Driver function ; Function call | #include <bits/stdc++.h> NEW_LINE #define N 4 NEW_LINE using namespace std ; bool isScalarMatrix ( int mat [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) if ( ( i != j ) && ( mat [ i ] [ j ] != 0 ) ) return false ; for ( int i = 0 ; i < N - 1 ; i ++ ) if ( mat [ i ] [ i ] != mat [ i + 1 ] [ i + 1 ] ) return false ; return true ; } int main ( ) { int mat [ N ] [ N ] = { { 2 , 0 , 0 , 0 } , { 0 , 2 , 0 , 0 } , { 0 , 0 , 2 , 0 } , { 0 , 0 , 0 , 2 } } ; if ( isScalarMatrix ( mat ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Construct a Binary Tree from Postorder and Inorder | C ++ program to construct tree using inorder and postorder traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Utility function to create a new node ; Recursive function to construct binary of size n from Inorder traversal in [ ] and Postorder traversal post [ ] . Initial values of inStrt and inEnd should be 0 and n - 1. The function doesn 't do any error checking for cases where inorder and postorder do not form a tree ; Base case ; Pick current node from Postorder traversal using postIndex and decrement postIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; This function mainly initializes index of root and calls buildUtil ( ) ; Function to find index of value in arr [ start ... end ] The function assumes that value is postsent in in [ ] ; Helper function that allocates a new node ; This funtcion is here just to test ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) ; int search ( int arr [ ] , int strt , int end , int value ) ; Node * buildUtil ( int in [ ] , int post [ ] , int inStrt , int inEnd , int * pIndex ) { if ( inStrt > inEnd ) return NULL ; Node * node = newNode ( post [ * pIndex ] ) ; ( * pIndex ) -- ; if ( inStrt == inEnd ) return node ; int iIndex = search ( in , inStrt , inEnd , node -> data ) ; node -> right = buildUtil ( in , post , iIndex + 1 , inEnd , pIndex ) ; node -> left = buildUtil ( in , post , inStrt , iIndex - 1 , pIndex ) ; return node ; } Node * buildTree ( int in [ ] , int post [ ] , int n ) { int pIndex = n - 1 ; return buildUtil ( in , post , 0 , n - 1 , & pIndex ) ; } int search ( int arr [ ] , int strt , int end , int value ) { int i ; for ( i = strt ; i <= end ; i ++ ) { if ( arr [ i ] == value ) break ; } return i ; } Node * newNode ( int data ) { Node * node = ( Node * ) malloc ( sizeof ( Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void preOrder ( Node * node ) { if ( node == NULL ) return ; printf ( " % d β " , node -> data ) ; preOrder ( node -> left ) ; preOrder ( node -> right ) ; } int main ( ) { int in [ ] = { 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 } ; int post [ ] = { 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int n = sizeof ( in ) / sizeof ( in [ 0 ] ) ; Node * root = buildTree ( in , post , n ) ; cout << " Preorder β of β the β constructed β tree β : β STRNEWLINE " ; preOrder ( root ) ; return 0 ; } |
Check given matrix is magic square or not | C ++ program to check whether a given matrix is magic matrix or not ; Returns true if mat [ ] [ ] is magic square , else returns false . ; calculate the sum of the prime diagonal ; the secondary diagonal ; For sums of Rows ; check if every row sum is equal to prime diagonal sum ; For sums of Columns ; check if every column sum is equal to prime diagonal sum ; driver program to test above function | #include <bits/stdc++.h> NEW_LINE #define N 3 NEW_LINE using namespace std ; bool isMagicSquare ( int mat [ ] [ N ] ) { int sum = 0 , sum2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum = sum + mat [ i ] [ i ] ; for ( int i = 0 ; i < N ; i ++ ) sum2 = sum2 + mat [ i ] [ N - 1 - i ] ; if ( sum != sum2 ) return false ; for ( int i = 0 ; i < N ; i ++ ) { int rowSum = 0 ; for ( int j = 0 ; j < N ; j ++ ) rowSum += mat [ i ] [ j ] ; if ( rowSum != sum ) return false ; } for ( int i = 0 ; i < N ; i ++ ) { int colSum = 0 ; for ( int j = 0 ; j < N ; j ++ ) colSum += mat [ j ] [ i ] ; if ( sum != colSum ) return false ; } return true ; } int main ( ) { int mat [ ] [ N ] = { { 2 , 7 , 6 } , { 9 , 5 , 1 } , { 4 , 3 , 8 } } ; if ( isMagicSquare ( mat ) ) cout << " Magic β Square " ; else cout << " Not β a β magic β Square " ; return 0 ; } |
Count sub | C ++ implementation to count sub - matrices having sum divisible by the value ' k ' ; function to count all sub - arrays divisible by k ; create auxiliary hash array to count frequency of remainders ; 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 ; as the sum can be negative , taking modulo twice ; Initialize result ; Traverse mod [ ] ; If there are more than one prefix subarrays with a particular mod value . ; add the subarrays starting from the arr [ i ] which are divisible by k itself ; function to count all sub - matrices having sum divisible by the value ' k ' ; Variable to store the final output ; Set the left column ; Initialize all elements of temp as 0 ; Set the right column for the left column set by outer loop ; Calculate sum between current left and right for every row ' i ' ; Count number of subarrays in temp [ ] having sum divisible by ' k ' and then add it to ' tot _ count ' ; required count of sub - matrices having sum divisible by ' k ' ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 10 NEW_LINE int subCount ( int arr [ ] , int n , int k ) { int mod [ k ] ; memset ( mod , 0 , sizeof ( mod ) ) ; int cumSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { cumSum += arr [ i ] ; mod [ ( ( cumSum % k ) + k ) % k ] ++ ; } int result = 0 ; for ( int i = 0 ; i < k ; i ++ ) if ( mod [ i ] > 1 ) result += ( mod [ i ] * ( mod [ i ] - 1 ) ) / 2 ; result += mod [ 0 ] ; return result ; } int countSubmatrix ( int mat [ SIZE ] [ SIZE ] , int n , int k ) { int tot_count = 0 ; int left , right , i ; int temp [ n ] ; for ( left = 0 ; left < n ; left ++ ) { memset ( temp , 0 , sizeof ( temp ) ) ; for ( right = left ; right < n ; right ++ ) { for ( i = 0 ; i < n ; ++ i ) temp [ i ] += mat [ i ] [ right ] ; tot_count += subCount ( temp , n , k ) ; } } return tot_count ; } 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 ; } |
Minimum operations required to make each row and column of matrix equals | C ++ Program to Find minimum number of operation required such that sum of elements on each row and column becomes same ; Function to find minimum operation required to make sum of each row and column equals ; Initialize the sumRow [ ] and sumCol [ ] array to 0 ; Calculate sumRow [ ] and sumCol [ ] array ; Find maximum sum value in either row or in column ; Find minimum increment required in either row or column ; Add difference in corresponding cell , sumRow [ ] and sumCol [ ] array ; Update the count variable ; If ith row satisfied , increment ith value for next iteration ; If jth column satisfied , increment jth value for next iteration ; Utility function to print matrix ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinOpeartion ( int matrix [ ] [ 2 ] , int n ) { int sumRow [ n ] , sumCol [ n ] ; memset ( sumRow , 0 , sizeof ( sumRow ) ) ; memset ( sumCol , 0 , sizeof ( sumCol ) ) ; for ( int i = 0 ; i < n ; ++ i ) for ( int j = 0 ; j < n ; ++ j ) { sumRow [ i ] += matrix [ i ] [ j ] ; sumCol [ j ] += matrix [ i ] [ j ] ; } 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 ; ) { int diff = min ( maxSum - sumRow [ i ] , maxSum - sumCol [ j ] ) ; matrix [ i ] [ j ] += diff ; sumRow [ i ] += diff ; sumCol [ j ] += diff ; count += diff ; if ( sumRow [ i ] == maxSum ) ++ i ; if ( sumCol [ j ] == maxSum ) ++ j ; } return count ; } 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 << " STRNEWLINE " ; } } int main ( ) { int matrix [ ] [ 2 ] = { { 1 , 2 } , { 3 , 4 } } ; cout << findMinOpeartion ( matrix , 2 ) << " STRNEWLINE " ; printMatrix ( matrix , 2 ) ; return 0 ; } |
Count frequency of k in a matrix of size n where matrix ( i , j ) = i + j | CPP program to find the frequency of k in matrix where m ( i , j ) = i + j ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( int n , int k ) { if ( n + 1 >= k ) return ( k - 1 ) ; else return ( 2 * n + 1 - k ) ; } int main ( ) { int n = 4 , k = 7 ; int freq = find ( n , k ) ; if ( freq < 0 ) cout << " β element β not β exist β STRNEWLINE β " ; else cout << " β Frequency β of β " << k << " β is β " << freq << " STRNEWLINE " ; return 0 ; } |
Given 1 ' s , β 2' s , 3 ' s β . . . . . . k ' s print them in zig zag way . | CPP program to print given number of 1 ' s , β 2' s , 3 ' s β . . . . k ' s in zig - zag way . ; function that prints given number of 1 ' s , β 2' s , 3 ' s β . . . . k ' s in zig - zag way . ; two - dimensional array to store numbers . ; for even row . ; for each column . ; storing element . ; decrement element at kth index . ; if array contains zero then increment index to make this next index ; for odd row . ; for each column . ; storing element . ; decrement element at kth index . ; if array contains zero then increment index to make this next index . ; printing the stored elements . ; Driver code for above function . | #include <bits/stdc++.h> NEW_LINE using namespace std ; void ZigZag ( int rows , int columns , int numbers [ ] ) { int k = 0 ; int arr [ rows ] [ columns ] ; for ( int i = 0 ; i < rows ; i ++ ) { if ( i % 2 == 0 ) { for ( int j = 0 ; j < columns and numbers [ k ] > 0 ; j ++ ) { arr [ i ] [ j ] = k + 1 ; numbers [ k ] -- ; if ( numbers [ k ] == 0 ) k ++ ; } } else { for ( int j = columns - 1 ; j >= 0 and numbers [ k ] > 0 ; j -- ) { arr [ i ] [ j ] = k + 1 ; numbers [ k ] -- ; if ( numbers [ k ] == 0 ) k ++ ; } } } for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < columns ; j ++ ) cout << arr [ i ] [ j ] << " β " ; cout << endl ; } } int main ( ) { int rows = 4 ; int columns = 5 ; int Numbers [ ] = { 3 , 4 , 2 , 2 , 3 , 1 , 5 } ; ZigZag ( rows , columns , Numbers ) ; return 0 ; } |
Number of cells a queen can move with obstacles on the chessborad | C ++ program to find number of cells a queen can move with obstacles on the chessborad ; Return the number of position a Queen can move . ; d11 , d12 , d21 , d22 are for diagnoal distances . r1 , r2 are for vertical distance . c1 , c2 are for horizontal distance . ; Initialise the distance to end of the board . ; For each obstacle find the minimum distance . If obstacle is present in any direction , distance will be updated . ; Driver code ; Chessboard size ; number of obstacles ; Queen x position ; Queen y position ; x position of obstacles ; y position of obstacles | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberofPosition ( int n , int k , int x , int y , int obstPosx [ ] , int obstPosy [ ] ) { int d11 , d12 , d21 , d22 , r1 , r2 , c1 , c2 ; d11 = min ( x - 1 , y - 1 ) ; d12 = min ( n - x , n - y ) ; d21 = min ( n - x , y - 1 ) ; d22 = min ( x - 1 , n - y ) ; r1 = y - 1 ; r2 = n - y ; c1 = x - 1 ; c2 = n - x ; for ( int i = 0 ; i < k ; i ++ ) { if ( x > obstPosx [ i ] && y > obstPosy [ i ] && x - obstPosx [ i ] == y - obstPosy [ i ] ) d11 = min ( d11 , x - obstPosx [ i ] - 1 ) ; if ( obstPosx [ i ] > x && obstPosy [ i ] > y && obstPosx [ i ] - x == obstPosy [ i ] - y ) d12 = min ( d12 , obstPosx [ i ] - x - 1 ) ; if ( obstPosx [ i ] > x && y > obstPosy [ i ] && obstPosx [ i ] - x == y - obstPosy [ i ] ) d21 = min ( d21 , obstPosx [ i ] - x - 1 ) ; if ( x > obstPosx [ i ] && obstPosy [ i ] > y && x - obstPosx [ i ] == obstPosy [ i ] - y ) d22 = min ( d22 , x - obstPosx [ i ] - 1 ) ; if ( x == obstPosx [ i ] && obstPosy [ i ] < y ) r1 = min ( r1 , y - obstPosy [ i ] - 1 ) ; if ( x == obstPosx [ i ] && obstPosy [ i ] > y ) r2 = min ( r2 , obstPosy [ i ] - y - 1 ) ; if ( y == obstPosy [ i ] && obstPosx [ i ] < x ) c1 = min ( c1 , x - obstPosx [ i ] - 1 ) ; if ( y == obstPosy [ i ] && obstPosx [ i ] > x ) c2 = min ( c2 , obstPosx [ i ] - x - 1 ) ; } return d11 + d12 + d21 + d22 + r1 + r2 + c1 + c2 ; } int main ( void ) { int n = 8 ; int k = 1 ; int Qposx = 4 ; int Qposy = 4 ; int obstPosx [ ] = { 3 } ; int obstPosy [ ] = { 5 } ; cout << numberofPosition ( n , k , Qposx , Qposy , obstPosx , obstPosy ) ; return 0 ; } |
Maximum product of 4 adjacent elements in matrix | C ++ program to find out the maximum product in the matrix which four elements are adjacent to each other in one direction ; function to find max product ; iterate the rows . ; iterate the columns . ; check the maximum product in horizontal row . ; check the maximum product in vertical row . ; check the maximum product in diagonal ( going through down - right ) ; check the maximum product in diagonal ( going through up - right ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 5 ; int FindMaxProduct ( int arr [ ] [ n ] , int n ) { int max = 0 , result ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { 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 ; } 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 ; } 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 ; } if ( ( i - 3 ) >= 0 && ( j - 1 ) <= 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 ; } int main ( ) { 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 ; } |
Maximum product of 4 adjacent elements in matrix | C ++ implemenation of the above approach ; Window Product for each row . ; Maximum window product for each row ; Global maximum window product ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE 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 ) { int wp ( 1 ) ; for ( int l = 0 ; l < k ; ++ l ) { wp *= a [ i ] [ l ] ; } mp = wp ; for ( int j = k ; j < m ; ++ j ) { wp = wp * a [ i ] [ j ] / a [ i ] [ j - k ] ; maxi = max ( maxi , max ( mp , wp ) ) ; } } return maxi ; } 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 ; } |
Construct a Binary Tree from Postorder and Inorder | C ++ program to construct tree using inorder and postorder traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Utility function to create a new node ; Recursive function to construct binary of size n from Inorder traversal in [ ] and Postorder traversal post [ ] . Initial values of inStrt and inEnd should be 0 and n - 1. The function doesn 't do any error checking for cases where inorder and postorder do not form a tree ; Base case ; Pick current node from Postorder traversal using postIndex and decrement postIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; This function mainly creates an unordered_map , then calls buildTreeUtil ( ) ; Store indexes of all items so that we we can quickly find later ; Index in postorder ; Helper function that allocates a new node ; This funtcion is here just to test ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) ; Node * buildUtil ( int in [ ] , int post [ ] , int inStrt , int inEnd , int * pIndex , unordered_map < int , int > & mp ) { if ( inStrt > inEnd ) return NULL ; int curr = post [ * pIndex ] ; Node * node = newNode ( curr ) ; ( * pIndex ) -- ; if ( inStrt == inEnd ) return node ; int iIndex = mp [ curr ] ; node -> right = buildUtil ( in , post , iIndex + 1 , inEnd , pIndex , mp ) ; node -> left = buildUtil ( in , post , inStrt , iIndex - 1 , pIndex , mp ) ; return node ; } struct Node * buildTree ( int in [ ] , int post [ ] , int len ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < len ; i ++ ) mp [ in [ i ] ] = i ; int index = len - 1 ; return buildUtil ( in , post , 0 , len - 1 , & index , mp ) ; } Node * newNode ( int data ) { Node * node = ( Node * ) malloc ( sizeof ( Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void preOrder ( Node * node ) { if ( node == NULL ) return ; printf ( " % d β " , node -> data ) ; preOrder ( node -> left ) ; preOrder ( node -> right ) ; } int main ( ) { int in [ ] = { 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 } ; int post [ ] = { 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int n = sizeof ( in ) / sizeof ( in [ 0 ] ) ; Node * root = buildTree ( in , post , n ) ; cout << " Preorder β of β the β constructed β tree β : β STRNEWLINE " ; preOrder ( root ) ; return 0 ; } |
Minimum flip required to make Binary Matrix symmetric | CPP Program to find minimum flip required to make Binary Matrix symmetric along main diagonal ; Return the minimum flip required to make Binary Matrix symmetric along main diagonal . ; finding the transpose of the matrix ; Finding the number of position where element are not same . ; Driver Program | #include <bits/stdc++.h> NEW_LINE #define N 3 NEW_LINE using namespace std ; int minimumflip ( int mat [ ] [ N ] , int n ) { int transpose [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) transpose [ i ] [ j ] = mat [ j ] [ i ] ; int flip = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( transpose [ i ] [ j ] != mat [ i ] [ j ] ) flip ++ ; return flip / 2 ; } int main ( ) { int n = 3 ; int mat [ N ] [ N ] = { { 0 , 0 , 1 } , { 1 , 1 , 1 } , { 1 , 0 , 0 } } ; cout << minimumflip ( mat , n ) << endl ; return 0 ; } |
Minimum flip required to make Binary Matrix symmetric | CPP Program to find minimum flip required to make Binary Matrix symmetric along main diagonal ; Return the minimum flip required to make Binary Matrix symmetric along main diagonal . ; Comparing elements across diagonal ; Driver Program | #include <bits/stdc++.h> NEW_LINE #define N 3 NEW_LINE using namespace std ; int minimumflip ( int mat [ ] [ N ] , int n ) { int flip = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( mat [ i ] [ j ] != mat [ j ] [ i ] ) flip ++ ; return flip ; } int main ( ) { int n = 3 ; int mat [ N ] [ N ] = { { 0 , 0 , 1 } , { 1 , 1 , 1 } , { 1 , 0 , 0 } } ; cout << minimumflip ( mat , n ) << endl ; return 0 ; } |
Frequencies of even and odd numbers in a matrix | C ++ Program to Find the frequency of even and odd numbers in a matrix ; function for calculating frequency ; modulo by 2 to check even and odd ; print Frequency of numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE 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 ) { if ( ( ar [ i ] [ j ] % 2 ) == 0 ) ++ even ; else ++ odd ; } } printf ( " β Frequency β of β odd β number β = β % d β STRNEWLINE " , odd ) ; printf ( " β Frequency β of β even β number β = β % d β STRNEWLINE " , even ) ; } 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 ; } |
Center element of matrix equals sums of half diagonals | C ++ Program to check if the center element is equal to the individual sum of all the half diagonals ; Function to Check center element is equal to the individual sum of all the half diagonals ; Find sums of half diagonals ; Driver code | #include <stdio.h> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; bool HalfDiagonalSums ( int mat [ ] [ MAX ] , int n ) { 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 ] ) ; } 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 ; } |
Program for Identity Matrix | C ++ program to print Identity Matrix ; Checking if row is equal to column ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Identity ( int num ) { int row , col ; for ( row = 0 ; row < num ; row ++ ) { for ( col = 0 ; col < num ; col ++ ) { if ( row == col ) cout << 1 << " β " ; else cout << 0 << " β " ; } cout << endl ; } return 0 ; } int main ( ) { int size = 5 ; Identity ( size ) ; return 0 ; } |
Program for Identity Matrix | CPP program to check if a given matrix is identity ; Driver Code | #include <iostream> NEW_LINE 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 ; } 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 ; } |
Ways of filling matrix such that product of all rows and all columns are equal to unity | CPP program to find number of ways to fill a matrix under given constraints ; Returns a raised power t under modulo mod ; Counting number of ways of filling the matrix ; Function calculating the answer ; if sum of numbers of rows and columns is odd i . e ( n + m ) % 2 == 1 and k = - 1 then there are 0 ways of filiing the matrix . ; If there is one row or one column then there is only one way of filling the matrix ; If the above cases are not followed then we find ways to fill the n - 1 rows and m - 1 columns which is 2 ^ ( ( m - 1 ) * ( n - 1 ) ) . ; Driver function for the program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 100000007 NEW_LINE long long modPower ( long long a , long long t ) { long long now = a , ret = 1 ; while ( t ) { if ( t & 1 ) ret = now * ( ret % mod ) ; now = now * ( now % mod ) ; t >>= 1 ; } return ret ; } long countWays ( int n , int m , int k ) { if ( k == -1 && ( n + m ) % 2 == 1 ) return 0 ; if ( n == 1 m == 1 ) return 1 ; return ( modPower ( modPower ( ( long long ) 2 , n - 1 ) , m - 1 ) % mod ) ; } int main ( ) { int n = 2 , m = 7 , k = 1 ; cout << countWays ( n , m , k ) ; return 0 ; } |
Construct a Binary Tree from Postorder and Inorder | C ++ program for above approach ; Node class ; Constructor ; Tree building function ; Create Stack of type Node * ; Create Set of type Node * ; Initialise postIndex with n - 1 ; Initialise root with NULL ; Initialise node with NULL ; Run do - while loop ; Initialise node with new Node ( post [ p ] ) ; ; Check is root is equal to NULL ; If size of set is greater than 0 ; If st . top ( ) is present in the set s ; If the stack is not empty and st . top ( ) -> data is equal to in [ i ] ; Pop elements from stack ; if node not equal to NULL ; Return root ; for print preOrder Traversal ; Driver Code ; Function Call ; Function Call for preOrder | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; Node ( int x ) { data = x ; left = right = NULL ; } } ; Node * buildTree ( int in [ ] , int post [ ] , int n ) { stack < Node * > st ; set < Node * > s ; int postIndex = n - 1 ; Node * root = NULL ; for ( int p = n - 1 , i = n - 1 ; p >= 0 ; ) { Node * node = NULL ; do { node = new Node ( post [ p ] ) ; if ( root == NULL ) { root = node ; } if ( st . size ( ) > 0 ) { if ( s . find ( st . top ( ) ) != s . end ( ) ) { s . erase ( st . top ( ) ) ; st . top ( ) -> left = node ; st . pop ( ) ; } else { st . top ( ) -> right = node ; } } st . push ( node ) ; } while ( post [ p -- ] != in [ i ] && p >= 0 ) ; node = NULL ; while ( st . size ( ) > 0 && i >= 0 && st . top ( ) -> data == in [ i ] ) { node = st . top ( ) ; st . pop ( ) ; i -- ; } if ( node != NULL ) { s . insert ( node ) ; st . push ( node ) ; } } return root ; } void preOrder ( Node * node ) { if ( node == NULL ) return ; printf ( " % d β " , node -> data ) ; preOrder ( node -> left ) ; preOrder ( node -> right ) ; } int main ( ) { int in [ ] = { 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 } ; int post [ ] = { 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int n = sizeof ( in ) / sizeof ( in [ 0 ] ) ; Node * root = buildTree ( in , post , n ) ; cout << " Preorder β of β the β constructed STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL tree β : β STRNEWLINE " ; preOrder ( root ) ; return 0 ; } |
Mirror of matrix across diagonal | Simple CPP program to find mirror of matrix across diagonal . ; for diagonal which start from at first row of matrix ; traverse all top right diagonal ; here we use stack for reversing the element of diagonal ; push all element back to matrix in reverse order ; do the same process for all the diagonal which start from last column ; here we use stack for reversing the elements of diagonal ; push all element back to matrix in reverse order ; Utility function to print a matrix ; driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; void imageSwap ( int mat [ ] [ MAX ] , int n ) { int row = 0 ; for ( int j = 0 ; j < n ; j ++ ) { stack < int > s ; int i = row , k = j ; while ( i < n && k >= 0 ) s . push ( mat [ i ++ ] [ k -- ] ) ; i = row , k = j ; while ( i < n && k >= 0 ) { mat [ i ++ ] [ k -- ] = s . top ( ) ; s . pop ( ) ; } } int column = n - 1 ; for ( int j = 1 ; j < n ; j ++ ) { stack < int > s ; int i = j , k = column ; while ( i < n && k >= 0 ) s . push ( mat [ i ++ ] [ k -- ] ) ; i = j ; k = column ; while ( i < n && k >= 0 ) { mat [ i ++ ] [ k -- ] = s . top ( ) ; s . pop ( ) ; } } } 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 ; } } 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 ; } |
Mirror of matrix across diagonal | Efficient CPP program to find mirror of matrix across diagonal . ; traverse a matrix and swap mat [ i ] [ j ] with mat [ j ] [ i ] ; Utility function to print a matrix ; driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; void imageSwap ( int mat [ ] [ MAX ] , int n ) { 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 ] ) ; } 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 ; } } 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 ; } |
Find all rectangles filled with 0 | C ++ program for the above approach ; flag to check column edge case , initializing with 0 ; flag to check row edge case , initializing with 0 ; loop breaks where first 1 encounters ; set the flag ; pass because already processed ; loop breaks where first 1 encounters ; set the flag ; fill rectangle elements with any number so that we can exclude next time ; when end point touch the boundary ; when end point touch the boundary ; retrieving the column size of array ; output array where we are going to store our output ; It will be used for storing start and end location in the same index ; storing initial position of rectangle ; will be used for the last position ; Driver code | #include <bits/stdc++.h> NEW_LINE 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 ( ) ; int flagc = 0 ; int flagr = 0 ; int n , m ; for ( m = i ; m < x ; m ++ ) { if ( a [ m ] [ j ] == 1 ) { flagr = 1 ; break ; } if ( a [ m ] [ j ] == 5 ) continue ; for ( n = j ; n < y ; n ++ ) { if ( a [ m ] [ n ] == 1 ) { flagc = 1 ; break ; } a [ m ] [ n ] = 5 ; } } if ( flagr == 1 ) output [ index ] . push_back ( m - 1 ) ; else output [ index ] . push_back ( m ) ; if ( flagc == 1 ) output [ index ] . push_back ( n - 1 ) ; else output [ index ] . push_back ( n ) ; } void get_rectangle_coordinates ( vector < vector < int > > a ) { int size_of_array = a . size ( ) ; vector < vector < int > > output ; 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 ) { output . push_back ( { i , j } ) ; 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 << " ] " ; } 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 ; } |
Search in a row wise and column wise sorted matrix | C ++ program to search an element in row - wise and column - wise sorted matrix ; 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 ; traverse through the matrix ; if the element is found ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int search ( int mat [ 4 ] [ 4 ] , int n , int x ) { if ( n == 0 ) return -1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) if ( mat [ i ] [ j ] == x ) { cout << " Element β found β at β ( " << i << " , β " << j << " ) STRNEWLINE " ; return 1 ; } } cout << " n β Element β not β found " ; return 0 ; } int main ( ) { int mat [ 4 ] [ 4 ] = { { 10 , 20 , 30 , 40 } , { 15 , 25 , 35 , 45 } , { 27 , 29 , 37 , 48 } , { 32 , 33 , 39 , 50 } } ; search ( mat , 4 , 29 ) ; return 0 ; } |
Search in a row wise and column wise sorted matrix | C ++ program to search an element in row - wise and column - wise sorted matrix ; 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 ; set indexes for top right element ; Check if mat [ i ] [ j ] < x ; if ( i == n j == - 1 ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; int i = 0 , j = n - 1 ; while ( i < n && j >= 0 ) { if ( mat [ i ] [ j ] == x ) { cout << " n β Found β at β " << i << " , β " << j ; return 1 ; } if ( mat [ i ] [ j ] > x ) j -- ; else i ++ ; } cout << " n β Element β not β found " ; return 0 ; } int main ( ) { int mat [ 4 ] [ 4 ] = { { 10 , 20 , 30 , 40 } , { 15 , 25 , 35 , 45 } , { 27 , 29 , 37 , 48 } , { 32 , 33 , 39 , 50 } } ; search ( mat , 4 , 29 ) ; return 0 ; } |
Zigzag ( or diagonal ) traversal of Matrix | ; 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 diagnols ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE #define R 5 NEW_LINE #define C 4 NEW_LINE using namespace std ; void diagonalOrder ( int arr [ ] [ C ] , int n , int m ) { 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 ; } } int main ( ) { 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 } , } ; diagonalOrder ( arr , n , m ) ; return 0 ; } |
Minimum cost to sort a matrix of numbers from 0 to n ^ 2 | C ++ implementation to find the total energy required to rearrange the numbers ; function to find the total energy required to rearrange the numbers ; nested loops to access the elements of the given matrix ; store quotient ; final destination location ( i_des , j_des ) of the element mat [ i ] [ j ] is being calculated ; energy required for the movement of the element mat [ i ] [ j ] is calculated and then accumulated in the ' tot _ energy ' ; required total energy ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 100 NEW_LINE int calculateEnergy ( int mat [ SIZE ] [ SIZE ] , int n ) { int i_des , j_des , q ; int tot_energy = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { q = mat [ i ] [ j ] / n ; i_des = q ; j_des = mat [ i ] [ j ] - ( n * q ) ; tot_energy += abs ( i_des - i ) + abs ( j_des - j ) ; } } return tot_energy ; } 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 ; } |
Unique cells in a binary matrix | C ++ program to count unique cells in a matrix ; Returns true if mat [ i ] [ j ] is unique ; checking in row calculating sumrow will be moving column wise ; checking in column calculating sumcol will be moving row wise ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; bool isUnique ( int mat [ ] [ MAX ] , int i , int j , int n , int m ) { int sumrow = 0 ; for ( int k = 0 ; k < m ; k ++ ) { sumrow += mat [ i ] [ k ] ; if ( sumrow > 1 ) return false ; } 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 ; } int main ( ) { int mat [ ] [ MAX ] = { { 0 , 1 , 0 , 0 } , { 0 , 0 , 1 , 0 } , { 1 , 0 , 0 , 1 } } ; cout << countUnique ( mat , 3 , 4 ) ; return 0 ; } |
Unique cells in a binary matrix | Efficient C ++ program to count unique cells in a binary matrix ; Count number of 1 s in each row and in each column ; Using above count arrays , find cells ; Driver code | #include <bits/stdc++.h> NEW_LINE 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 ) ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( mat [ i ] [ j ] ) { rowsum [ i ] ++ ; colsum [ j ] ++ ; } 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 ; } int main ( ) { int mat [ ] [ MAX ] = { { 0 , 1 , 0 , 0 } , { 0 , 0 , 1 , 0 } , { 1 , 0 , 0 , 1 } } ; cout << countUnique ( mat , 3 , 4 ) ; return 0 ; } |
Check if a given matrix is sparse or not | CPP code to check if a matrix is sparse . ; Count number of zeros in the matrix ; Driver Function | #include <iostream> NEW_LINE using namespace std ; const int MAX = 100 ; bool isSparse ( int array [ ] [ MAX ] , int m , int n ) { int counter = 0 ; 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 ) ) ; } 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 " ; } |
Row | CPP program to find common elements in two diagonals . ; Returns count of row wise same elements in two diagonals of mat [ n ] [ n ] ; Driver Code | #include <iostream> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; 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 ; } int main ( ) { int mat [ ] [ MAX ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; cout << countCommon ( mat , 3 ) ; return 0 ; } |
Check if sums of i | ; Function to check the if sum of a row is same as corresponding column ; Driver Code ; number of rows ; number of columns | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; bool areSumSame ( int a [ ] [ MAX ] , int n , int m ) { int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum1 = 0 , sum2 = 0 ; for ( int j = 0 ; j < m ; j ++ ) { sum1 += a [ i ] [ j ] ; sum2 += a [ j ] [ i ] ; } if ( sum1 == sum2 ) return true ; } return false ; } int main ( ) { int n = 4 ; int m = 4 ; 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 ) << " STRNEWLINE " ; return 0 ; } |
Creating a tree with Left | C ++ program to create a tree with left child right sibling representation . ; Creating new Node ; Adds a sibling to a list with starting with n ; Add child Node to a Node ; Check if child list is not empty . ; Traverses tree in depth first order ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; struct Node * child ; } ; Node * newNode ( int data ) { Node * newNode = new Node ; newNode -> next = newNode -> child = NULL ; newNode -> data = data ; return newNode ; } Node * addSibling ( Node * n , int data ) { if ( n == NULL ) return NULL ; while ( n -> next ) n = n -> next ; return ( n -> next = newNode ( data ) ) ; } Node * addChild ( Node * n , int data ) { if ( n == NULL ) return NULL ; if ( n -> child ) return addSibling ( n -> child , data ) ; else return ( n -> child = newNode ( data ) ) ; } void traverseTree ( Node * root ) { if ( root == NULL ) return ; while ( root ) { cout << " β " << root -> data ; if ( root -> child ) traverseTree ( root -> child ) ; root = root -> next ; } } int main ( ) { Node * root = newNode ( 10 ) ; Node * n1 = addChild ( root , 2 ) ; Node * n2 = addChild ( root , 3 ) ; Node * n3 = addChild ( root , 4 ) ; Node * n4 = addChild ( n3 , 6 ) ; Node * n5 = addChild ( root , 5 ) ; Node * n6 = addChild ( n5 , 7 ) ; Node * n7 = addChild ( n5 , 8 ) ; Node * n8 = addChild ( n5 , 9 ) ; traverseTree ( root ) ; return 0 ; } |
Find row number of a binary matrix having maximum number of 1 s | CPP program to find row with maximum 1 in row sorted binary matrix ; function for finding row with maximum 1 ; find left most position of 1 in a row find 1 st zero in a row ; driver program | #include <bits/stdc++.h> NEW_LINE #define N 4 NEW_LINE using namespace std ; void findMax ( int arr [ ] [ N ] ) { int row = 0 , i , j ; for ( i = 0 , j = N - 1 ; i < N ; i ++ ) { while ( arr [ i ] [ j ] == 1 && j >= 0 ) { row = i ; j -- ; } } cout << " Row β number β = β " << row + 1 ; cout << " , β MaxCount β = β " << N - 1 - j ; } 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 ; } |
Find if a 2 | C ++ program for the above approach ; function which tells all cells are visited or not ; starting cell values ; if we get { 0 , 0 } before the end of loop then returns false . Because it means we didn 't traverse all the cells ; If found cycle then return false ; Update startx and starty values to next cell values ; finally if we reach our goal then returns true ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isAllCellTraversed ( vector < vector < pair < int , int > > > grid , int n , int m ) { bool visited [ n ] [ m ] ; int total = n * m ; int startx = grid [ 0 ] [ 0 ] . first ; int starty = grid [ 0 ] [ 0 ] . second ; for ( int i = 0 ; i < total - 2 ; i ++ ) { if ( grid [ startx ] [ starty ] . first == -1 and grid [ startx ] [ starty ] . second == -1 ) 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 ; startx = x ; starty = y ; } if ( grid [ startx ] [ starty ] . first == -1 and grid [ startx ] [ starty ] . second == -1 ) return true ; return false ; } 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 ; } |
Print all palindromic paths from top left to bottom right in a matrix | C ++ program to print all palindromic paths from top left to bottom right in a grid . ; i and j are row and column indexes of current cell ( initially these are 0 and 0 ) . ; If we have not reached bottom right corner , keep exlporing ; If we reach bottom right corner , we check if if the path used is palindrome or not . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE bool isPalin ( string str ) { int len = str . length ( ) / 2 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] != str [ str . length ( ) - i - 1 ] ) return false ; } return true ; } void palindromicPath ( string str , char a [ ] [ N ] , int i , int j , int m , int n ) { if ( j < m - 1 i < n - 1 ) { if ( i < n - 1 ) palindromicPath ( str + a [ i ] [ j ] , a , i + 1 , j , m , n ) ; if ( j < m - 1 ) palindromicPath ( str + a [ i ] [ j ] , a , i , j + 1 , m , n ) ; } else { str = str + a [ n - 1 ] [ m - 1 ] ; if ( isPalin ( str ) ) cout << ( str ) << endl ; } } int main ( ) { char arr [ ] [ N ] = { { ' a ' , ' a ' , ' a ' , ' b ' } , { ' b ' , ' a ' , ' a ' , ' a ' } , { ' a ' , ' b ' , ' b ' , ' a ' } } ; string str = " " ; palindromicPath ( str , arr , 0 , 0 , 4 , 3 ) ; return 0 ; } |
Possible moves of knight | CPP program to find number of possible moves of knight ; To calculate possible moves ; All possible moves of a knight ; Check if each possible move is valid or not ; Position of knight after move ; count valid moves ; Return number of possible moves ; Driver program to check findPossibleMoves ( ) | #include <bits/stdc++.h> NEW_LINE #define n 4 NEW_LINE #define m 4 NEW_LINE using namespace std ; int findPossibleMoves ( int mat [ n ] [ m ] , int p , int q ) { 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 ; for ( int i = 0 ; i < 8 ; i ++ ) { int x = p + X [ i ] ; int y = q + Y [ i ] ; if ( x >= 0 && y >= 0 && x < n && y < m && mat [ x ] [ y ] == 0 ) count ++ ; } return count ; } 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 ; } |
Efficiently compute sums of diagonals of a matrix | A simple C ++ program to find sum of diagonals ; Condition for principal diagonal ; Condition for secondary diagonal ; Driver code | #include <bits/stdc++.h> NEW_LINE 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 ++ ) { if ( i == j ) principal += mat [ i ] [ j ] ; if ( ( i + j ) == ( n - 1 ) ) secondary += mat [ i ] [ j ] ; } } cout << " Principal β Diagonal : " << principal << endl ; cout << " Secondary β Diagonal : " << secondary << endl ; } 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 ; } |
Efficiently compute sums of diagonals of a matrix | An efficient C ++ program to find sum of diagonals ; Driver code | #include <bits/stdc++.h> NEW_LINE 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 ; } 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 ; } |
Creating a tree with Left | C ++ program to create a tree with left child right sibling representation . ; Creating new Node ; Adds a sibling to a list with starting with n ; Add child Node to a Node ; Check if child list is not empty . ; Traverses tree in level order ; Corner cases ; Create a queue and enque root ; Take out an item from the queue ; Print next level of taken out item and enque next level 's children ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; struct Node * child ; } ; Node * newNode ( int data ) { Node * newNode = new Node ; newNode -> next = newNode -> child = NULL ; newNode -> data = data ; return newNode ; } Node * addSibling ( Node * n , int data ) { if ( n == NULL ) return NULL ; while ( n -> next ) n = n -> next ; return ( n -> next = newNode ( data ) ) ; } Node * addChild ( Node * n , int data ) { if ( n == NULL ) return NULL ; if ( n -> child ) return addSibling ( n -> child , data ) ; else return ( n -> child = newNode ( data ) ) ; } void traverseTree ( Node * root ) { if ( root == NULL ) return ; cout << root -> data << " β " ; if ( root -> child == NULL ) return ; queue < Node * > q ; Node * curr = root -> child ; q . push ( curr ) ; while ( ! q . empty ( ) ) { curr = q . front ( ) ; q . pop ( ) ; while ( curr != NULL ) { cout << curr -> data << " β " ; if ( curr -> child != NULL ) { q . push ( curr -> child ) ; } curr = curr -> next ; } } } int main ( ) { Node * root = newNode ( 10 ) ; Node * n1 = addChild ( root , 2 ) ; Node * n2 = addChild ( root , 3 ) ; Node * n3 = addChild ( root , 4 ) ; Node * n4 = addChild ( n3 , 6 ) ; Node * n5 = addChild ( root , 5 ) ; Node * n6 = addChild ( n5 , 7 ) ; Node * n7 = addChild ( n5 , 8 ) ; Node * n8 = addChild ( n5 , 9 ) ; traverseTree ( root ) ; return 0 ; } |
Boundary elements of a Matrix | C ++ program to print boundary element of matrix . ; Driver code | #include <bits/stdc++.h> NEW_LINE 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 << " STRNEWLINE " ; } } int main ( ) { int a [ 4 ] [ MAX ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } } ; printBoundary ( a , 4 , 4 ) ; return 0 ; } |
Boundary elements of a Matrix | C ++ program to find sum of boundary elements of matrix . ; Driver code | #include <bits/stdc++.h> NEW_LINE 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 ; } int main ( ) { int a [ ] [ MAX ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } } ; long long int sum = getBoundarySum ( a , 4 , 4 ) ; cout << " Sum β of β boundary β elements β is β " << sum ; return 0 ; } |
Print a matrix in a spiral form starting from a point | C ++ program to print a matrix in spiral form . ; Driver code ; Function calling | #include <iostream> NEW_LINE 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 ; } int main ( ) { int mat [ ] [ MAX ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int r = 3 , c = 3 ; printSpiral ( mat , r , c ) ; } |
Find difference between sums of two diagonals | C ++ program to find the difference between the sum of diagonal . ; Initialize sums of diagonals ; finding sum of primary diagonal ; finding sum of secondary diagonal ; Absolute difference of the sums across the diagonals ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; int difference ( int arr [ ] [ MAX ] , int n ) { int d1 = 0 , d2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i == j ) d1 += arr [ i ] [ j ] ; if ( i == n - j - 1 ) d2 += arr [ i ] [ j ] ; } } return abs ( d1 - d2 ) ; } int main ( ) { int n = 3 ; int arr [ ] [ MAX ] = { { 11 , 2 , 4 } , { 4 , 5 , 6 } , { 10 , 8 , -12 } } ; cout << difference ( arr , n ) ; return 0 ; } |
Find difference between sums of two diagonals | C ++ program to find the difference between the sum of diagonal . ; Initialize sums of diagonals ; Absolute difference of the sums across the diagonals ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; int difference ( int arr [ ] [ MAX ] , int n ) { int d1 = 0 , d2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { d1 += arr [ i ] [ i ] ; d2 += arr [ i ] [ n - i - 1 ] ; } return abs ( d1 - d2 ) ; } int main ( ) { int n = 3 ; int arr [ ] [ MAX ] = { { 11 , 2 , 4 } , { 4 , 5 , 6 } , { 10 , 8 , -12 } } ; cout << difference ( arr , n ) ; return 0 ; } |
Circular Matrix ( Construct a matrix with numbers 1 to m * n in spiral way ) | C ++ program to fill a matrix with values from 1 to n * n in spiral fashion . ; Fills a [ m ] [ n ] with values from 1 to m * n in spiral fashion . ; Initialize value to be filled in matrix ; k - starting row index m - ending row index l - starting column index n - ending column index ; Print the first row from the remaining rows ; Print the last column from the remaining columns ; Print the last row from the remaining rows ; Print the first column from the remaining columns ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; void spiralFill ( int m , int n , int a [ ] [ MAX ] ) { int val = 1 ; int k = 0 , l = 0 ; while ( k < m && l < n ) { for ( int i = l ; i < n ; ++ i ) a [ k ] [ i ] = val ++ ; k ++ ; for ( int i = k ; i < m ; ++ i ) a [ i ] [ n - 1 ] = val ++ ; n -- ; if ( k < m ) { for ( int i = n - 1 ; i >= l ; -- i ) a [ m - 1 ] [ i ] = val ++ ; m -- ; } if ( l < n ) { for ( int i = m - 1 ; i >= k ; -- i ) a [ i ] [ l ] = val ++ ; l ++ ; } } } 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 ; } |
Prufer Code to Tree Creation | C ++ program to construct tree from given Prufer Code ; Prints edges of tree represented by give Prufer code ; Initialize the array of vertices ; Number of occurrences of vertex in code ; Find the smallest label not present in prufer [ ] . ; If j + 1 is not present in prufer set ; Remove from Prufer set and print pair . ; For the last element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printTreeEdges ( int prufer [ ] , int m ) { int vertices = m + 2 ; int vertex_set [ vertices ] ; for ( int i = 0 ; i < vertices ; i ++ ) vertex_set [ i ] = 0 ; for ( int i = 0 ; i < vertices - 2 ; i ++ ) vertex_set [ prufer [ i ] - 1 ] += 1 ; cout << " The edge set E ( G ) is : " int j = 0 ; for ( int i = 0 ; i < vertices - 2 ; i ++ ) { for ( j = 0 ; j < vertices ; j ++ ) { if ( vertex_set [ j ] == 0 ) { vertex_set [ j ] = -1 ; cout << " ( " << ( j + 1 ) << " , β " << prufer [ i ] << " ) β " ; vertex_set [ prufer [ i ] - 1 ] -- ; break ; } } } j = 0 ; for ( int i = 0 ; i < vertices ; i ++ ) { if ( vertex_set [ i ] == 0 && j == 0 ) { cout << " ( " << ( i + 1 ) << " , β " ; j ++ ; } else if ( vertex_set [ i ] == 0 && j == 1 ) cout << ( i + 1 ) << " ) STRNEWLINE " ; } } int main ( ) { int prufer [ ] = { 4 , 1 , 3 , 4 } ; int n = sizeof ( prufer ) / sizeof ( prufer [ 0 ] ) ; printTreeEdges ( prufer , n ) ; return 0 ; } |
Maximum and Minimum in a square matrix . | C ++ program for finding maximum and minimum in a matrix . ; Finds maximum and minimum in arr [ 0. . n - 1 ] [ 0. . n - 1 ] using pair wise comparisons ; Traverses rows one by one ; Compare elements from beginning and end of current row ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE void maxMin ( int arr [ ] [ MAX ] , int n ) { int min = INT_MAX ; int max = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= n / 2 ; j ++ ) { 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 ; } int main ( ) { int arr [ MAX ] [ MAX ] = { 5 , 9 , 11 , 25 , 0 , 14 , 21 , 6 , 4 } ; maxMin ( arr , 3 ) ; return 0 ; } |
Print matrix in antispiral form | C ++ program to print matrix in anti - spiral form ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Print the first row from the remaining rows ; Print the last column from the remaining columns ; Print the last row from the remaining rows ; Print the first column from the remaining columns ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 4 NEW_LINE #define C 5 NEW_LINE void antiSpiralTraversal ( int m , int n , int a [ R ] [ C ] ) { int i , k = 0 , l = 0 ; stack < int > stk ; while ( k <= m && l <= n ) { for ( i = l ; i <= n ; ++ i ) stk . push ( a [ k ] [ i ] ) ; k ++ ; for ( i = k ; i <= m ; ++ i ) stk . push ( a [ i ] [ n ] ) ; n -- ; if ( k <= m ) { for ( i = n ; i >= l ; -- i ) stk . push ( a [ m ] [ i ] ) ; m -- ; } if ( l <= n ) { for ( i = m ; i >= k ; -- i ) stk . push ( a [ i ] [ l ] ) ; l ++ ; } } while ( ! stk . empty ( ) ) { cout << stk . top ( ) << " β " ; stk . pop ( ) ; } } 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 ; } |
Minimum operations required to set all elements of binary matrix | C ++ program to find minimum operations required to set all the element of binary matrix ; Return minimum operation required to make all 1 s . ; check if this cell equals 0 ; increase the number of moves ; flip from this cell to the start point ; flip the cell ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define N 5 NEW_LINE #define M 5 NEW_LINE using namespace std ; 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 -- ) { if ( arr [ i ] [ j ] == 0 ) { ans ++ ; for ( int k = 0 ; k <= i ; k ++ ) { for ( int h = 0 ; h <= j ; h ++ ) { if ( arr [ k ] [ h ] == 1 ) arr [ k ] [ h ] = 0 ; else arr [ k ] [ h ] = 1 ; } } } } } return ans ; } 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 ; } |
C Program To Check whether Matrix is Skew Symmetric or not | C program to check whether given matrix is skew - symmetric or not ; Utility function to create transpose matrix ; Utility function to check skew - symmetric matrix condition ; Utility function to print a matrix ; Driver program to test above functions ; Function create transpose matrix ; Check whether matrix is skew - symmetric or not | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define ROW 3 NEW_LINE #define COL 3 NEW_LINE void transpose ( int transpose_matrix [ ROW ] [ COL ] , int matrix [ ROW ] [ COL ] ) { for ( int i = 0 ; i < ROW ; i ++ ) for ( int j = 0 ; j < COL ; j ++ ) transpose_matrix [ j ] [ i ] = matrix [ i ] [ j ] ; } bool check ( int transpose_matrix [ ROW ] [ COL ] , int matrix [ ROW ] [ COL ] ) { for ( int i = 0 ; i < ROW ; i ++ ) for ( int j = 0 ; j < COL ; j ++ ) if ( matrix [ i ] [ j ] != - transpose_matrix [ i ] [ j ] ) return false ; return true ; } void printMatrix ( int matrix [ ROW ] [ COL ] ) { for ( int i = 0 ; i < ROW ; i ++ ) { for ( int j = 0 ; j < COL ; j ++ ) printf ( " % d β " , matrix [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } int main ( ) { int matrix [ ROW ] [ COL ] = { { 0 , 5 , -4 } , { -5 , 0 , 1 } , { 4 , -1 , 0 } , } ; int transpose_matrix [ ROW ] [ COL ] ; transpose ( transpose_matrix , matrix ) ; printf ( " Transpose β matrix : β STRNEWLINE " ) ; printMatrix ( transpose_matrix ) ; if ( check ( transpose_matrix , matrix ) ) printf ( " Skew β Symmetric β Matrix " ) ; else printf ( " Not β Skew β Symmetric β Matrix " ) ; return 0 ; } |
Sum of matrix element where each elements is integer division of row and column | C ++ program to find sum of matrix element where each element is integer division of row and column . ; Return sum of matrix element where each element is division of its corresponding row and column . ; For each column . ; count the number of elements of each column . Initialize to i - 1 because number of zeroes are i - 1. ; For multiply ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int n ) { int ans = 0 , temp = 0 , num ; for ( int i = 1 ; i <= n && temp < n ; i ++ ) { temp = i - 1 ; num = 1 ; while ( temp < n ) { if ( temp + i <= n ) ans += ( i * num ) ; else ans += ( ( n - temp ) * num ) ; temp += i ; num ++ ; } } return ans ; } int main ( ) { int N = 2 ; cout << findSum ( N ) << endl ; return 0 ; } |
Find number of transformation to make two Matrix Equal | C ++ program to find number of countOpsation to make two matrix equals ; Update matrix A [ ] [ ] so that only A [ ] [ ] has to be countOpsed ; Check necessary condition for condition for existence of full countOpsation ; If countOpsation is possible calculate total countOpsation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; int countOps ( int A [ ] [ MAX ] , int B [ ] [ MAX ] , int m , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) A [ i ] [ j ] -= B [ i ] [ j ] ; 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 ; 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 ) ; } 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 ; } |
Construct the full k | C ++ program to build full k - ary tree from its preorder traversal and to print the postorder traversal of the tree . ; Structure of a node of an n - ary tree ; Utility function to create a new tree node with k children ; Function to build full k - ary tree ; For null tree ; For adding k children to a node ; Check if ind is in range of array Check if height of the tree is greater than 1 ; Recursively add each child ; Function to find the height of the tree ; Function to print postorder traversal of the tree ; Driver program to implement full k - ary tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; vector < Node * > child ; } ; Node * newNode ( int value ) { Node * nNode = new Node ; nNode -> key = value ; return nNode ; } Node * BuildKaryTree ( int A [ ] , int n , int k , int h , int & ind ) { if ( n <= 0 ) return NULL ; Node * nNode = newNode ( A [ ind ] ) ; if ( nNode == NULL ) { cout << " Memory β error " << endl ; return NULL ; } for ( int i = 0 ; i < k ; i ++ ) { if ( ind < n - 1 && h > 1 ) { ind ++ ; nNode -> child . push_back ( BuildKaryTree ( A , n , k , h - 1 , ind ) ) ; } else { nNode -> child . push_back ( NULL ) ; } } return nNode ; } Node * BuildKaryTree ( int * A , int n , int k , int ind ) { int height = ( int ) ceil ( log ( ( double ) n * ( k - 1 ) + 1 ) / log ( ( double ) k ) ) ; return BuildKaryTree ( A , n , k , height , ind ) ; } void postord ( Node * root , int k ) { if ( root == NULL ) return ; for ( int i = 0 ; i < k ; i ++ ) postord ( root -> child [ i ] , k ) ; cout << root -> key << " β " ; } int main ( ) { int ind = 0 ; int k = 3 , n = 10 ; int preorder [ ] = { 1 , 2 , 5 , 6 , 7 , 3 , 8 , 9 , 10 , 4 } ; Node * root = BuildKaryTree ( preorder , n , k , ind ) ; cout << " Postorder β traversal β of β constructed " " β full β k - ary β tree β is : β " ; postord ( root , k ) ; cout << endl ; return 0 ; } |
Form coils in a matrix | C ++ program to print 2 coils of a 4 n x 4 n matrix . ; Print coils in a matrix of size 4 n x 4 n ; Number of elements in each coil ; Let us fill elements in coil 1. ; First element of coil1 4 * n * 2 * n + 2 * n ; ; Fill remaining m - 1 elements in coil1 [ ] ; Fill elements of current step from down to up ; Next element from current element ; Fill elements of current step from up to down . ; get coil2 from coil1 ; Print both coils ; Driver code | #include <iostream> NEW_LINE using namespace std ; void printCoils ( int n ) { int m = 8 * n * n ; int coil1 [ m ] ; coil1 [ 0 ] = 8 * n * n + 2 * n ; int curr = coil1 [ 0 ] ; int nflg = 1 , step = 2 ; int index = 1 ; while ( index < m ) { for ( int i = 0 ; i < step ; i ++ ) { curr = coil1 [ index ++ ] = ( curr - 4 * n * nflg ) ; if ( index >= m ) break ; } if ( index >= m ) break ; for ( int i = 0 ; i < step ; i ++ ) { curr = coil1 [ index ++ ] = curr + nflg ; if ( index >= m ) break ; } nflg = nflg * ( -1 ) ; step += 2 ; } int coil2 [ m ] ; for ( int i = 0 ; i < 8 * n * n ; i ++ ) coil2 [ i ] = 16 * n * n + 1 - coil1 [ i ] ; cout << " Coil β 1 β : β " ; for ( int i = 0 ; i < 8 * n * n ; i ++ ) cout << coil1 [ i ] << " β " ; cout << " Coil 2 : " for ( int i = 0 ; i < 8 * n * n ; i ++ ) cout << coil2 [ i ] << " β " ; } int main ( ) { int n = 1 ; printCoils ( n ) ; return 0 ; } |
Sum of matrix in which each element is absolute difference of its row and column numbers | C ++ program to find sum of matrix in which each element is absolute difference of its corresponding row and column number row . ; Retuen the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Generate matrix ; Compute sum ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int n ) { int arr [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) arr [ i ] [ j ] = abs ( i - j ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) sum += arr [ i ] [ j ] ; return sum ; } int main ( ) { int n = 3 ; cout << findSum ( n ) << endl ; return 0 ; } |
Sum of matrix in which each element is absolute difference of its row and column numbers | C ++ program to find sum of matrix in which each element is absolute difference of its corresponding row and column number row . ; Retuen the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += i * ( n - i ) ; return 2 * sum ; } int main ( ) { int n = 3 ; cout << findSum ( n ) << endl ; return 0 ; } |
Sum of matrix in which each element is absolute difference of its row and column numbers | C ++ program to find sum of matrix in which each element is absolute difference of its corresponding row and column number row . ; Retuen the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int n ) { n -- ; int sum = 0 ; sum += ( n * ( n + 1 ) ) / 2 ; sum += ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; return sum ; } int main ( ) { int n = 3 ; cout << findSum ( n ) << endl ; return 0 ; } |
Sum of both diagonals of a spiral odd | C ++ program to find sum of diagonals of spiral matrix ; function returns sum of diagonals ; as order should be only odd we should pass only odd - integers ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int spiralDiaSum ( int n ) { if ( n == 1 ) return 1 ; return ( 4 * n * n - 6 * n + 6 + spiralDiaSum ( n - 2 ) ) ; } int main ( ) { int n = 7 ; cout << spiralDiaSum ( n ) ; return 0 ; } |
Find perimeter of shapes formed with 1 s in binary matrix | C ++ program to find perimeter of area coverede by 1 in 2D matrix consisits of 0 ' s β and β 1' s . ; Find the number of covered side for mat [ i ] [ j ] . ; UP ; LEFT ; DOWN ; RIGHT ; Returns sum of perimeter of shapes formed with 1 s ; Traversing the matrix and finding ones to calculate their contribution . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 3 NEW_LINE #define C 5 NEW_LINE int numofneighbour ( int mat [ ] [ C ] , int i , int j ) { int count = 0 ; if ( i > 0 && mat [ i - 1 ] [ j ] ) count ++ ; if ( j > 0 && mat [ i ] [ j - 1 ] ) count ++ ; if ( i < R - 1 && mat [ i + 1 ] [ j ] ) count ++ ; if ( j < C - 1 && mat [ i ] [ j + 1 ] ) count ++ ; return count ; } int findperimeter ( int mat [ R ] [ C ] ) { int perimeter = 0 ; for ( int i = 0 ; i < R ; i ++ ) for ( int j = 0 ; j < C ; j ++ ) if ( mat [ i ] [ j ] ) perimeter += ( 4 - numofneighbour ( mat , i , j ) ) ; return perimeter ; } int main ( ) { int mat [ R ] [ C ] = { 0 , 1 , 0 , 0 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , } ; cout << findperimeter ( mat ) << endl ; return 0 ; } |
Construct Binary Tree from String with bracket representation | C ++ program to construct a binary tree from the given string ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node ; This function is here just to test ; function to return the index of close parenthesis ; Inbuilt stack ; if open parenthesis , push it ; if close parenthesis ; if stack is empty , this is the required index ; if not found return - 1 ; function to construct tree from string ; Base case ; new root ; if next char is ' ( ' find the index of its complement ' ) ' ; if index found ; call for left subtree ; call for right subtree ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = ( Node * ) malloc ( sizeof ( Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void preOrder ( Node * node ) { if ( node == NULL ) return ; printf ( " % d β " , node -> data ) ; preOrder ( node -> left ) ; preOrder ( node -> right ) ; } int findIndex ( string str , int si , int ei ) { if ( si > ei ) return -1 ; stack < char > s ; for ( int i = si ; i <= ei ; i ++ ) { if ( str [ i ] == ' ( ' ) s . push ( str [ i ] ) ; else if ( str [ i ] == ' ) ' ) { if ( s . top ( ) == ' ( ' ) { s . pop ( ) ; if ( s . empty ( ) ) return i ; } } } return -1 ; } Node * treeFromString ( string str , int si , int ei ) { if ( si > ei ) return NULL ; Node * root = newNode ( str [ si ] - '0' ) ; int index = -1 ; if ( si + 1 <= ei && str [ si + 1 ] == ' ( ' ) index = findIndex ( str , si + 1 , ei ) ; if ( index != -1 ) { root -> left = treeFromString ( str , si + 2 , index - 1 ) ; root -> right = treeFromString ( str , index + 2 , ei - 1 ) ; } return root ; } int main ( ) { string str = "4(2(3 ) ( 1 ) ) (6(5 ) ) " ; Node * root = treeFromString ( str , 0 , str . length ( ) - 1 ) ; preOrder ( root ) ; } |
Continuous Tree | CPP Code to check if the tree is continuous or not ; Node structure ; Function to check if the tree is continuous or not ; If root is Null then tree isn 't Continuous ; BFS Traversal ; Move to left child ; if difference between parent and child is equal to 1 then do continue otherwise make flag = 0 and break ; Move to right child ; if difference between parent and child is equal to 1 then do continue otherwise make flag = 0 and break ; Driver Code ; Constructing the Tree ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int val ; node * left ; node * right ; node ( ) : val ( 0 ) , left ( nullptr ) , right ( nullptr ) { } node ( int x ) : val ( x ) , left ( nullptr ) , right ( nullptr ) { } node ( int x , node * left , node * right ) : val ( x ) , left ( left ) , right ( right ) { } } ; bool continuous ( struct node * root ) { if ( root == NULL ) return false ; int flag = 1 ; queue < struct node * > Q ; Q . push ( root ) ; node * temp ; while ( ! Q . empty ( ) ) { temp = Q . front ( ) ; Q . pop ( ) ; if ( temp -> left ) { if ( abs ( temp -> left -> val - temp -> val ) == 1 ) Q . push ( temp -> left ) ; else { flag = 0 ; break ; } } if ( temp -> right ) { if ( abs ( temp -> right -> val - temp -> val ) == 1 ) Q . push ( temp -> right ) ; else { flag = 0 ; break ; } } } if ( flag ) return true ; else return false ; } int main ( ) { struct node * root = new node ( 3 ) ; root -> left = new node ( 2 ) ; root -> right = new node ( 4 ) ; root -> left -> left = new node ( 1 ) ; root -> left -> right = new node ( 3 ) ; root -> right -> right = new node ( 5 ) ; if ( continuous ( root ) ) cout << " True STRNEWLINE " ; else cout << " False STRNEWLINE " ; return 0 ; } |
Print matrix in diagonal pattern | C ++ program to print matrix in diagonal order ; Initialize indexes of element to be printed next ; Direction is initially from down to up ; Traverse the matrix till all elements get traversed ; If isUp = true then traverse from downward to upward ; Set i and j according to direction ; If isUp = 0 then traverse up to down ; Set i and j according to direction ; Revert the isUp to change the direction ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; void printMatrixDiagonal ( int mat [ MAX ] [ MAX ] , int n ) { int i = 0 , j = 0 ; bool isUp = true ; for ( int k = 0 ; k < n * n ; ) { if ( isUp ) { for ( ; i >= 0 && j < n ; j ++ , i -- ) { cout << mat [ i ] [ j ] << " β " ; k ++ ; } if ( i < 0 && j <= n - 1 ) i = 0 ; if ( j == n ) i = i + 2 , j -- ; } else { for ( ; j >= 0 && i < n ; i ++ , j -- ) { cout << mat [ i ] [ j ] << " β " ; k ++ ; } if ( j < 0 && i <= n - 1 ) j = 0 ; if ( i == n ) j = j + 2 , i -- ; } isUp = ! isUp ; } } int main ( ) { int mat [ MAX ] [ MAX ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int n = 3 ; printMatrixDiagonal ( mat , n ) ; return 0 ; } |
Print matrix in diagonal pattern | C ++ program to print matrix in diagonal order ; Driver code ; Initialize matrix ; n - size mode - switch to derive up / down traversal it - iterator count - increases until it reaches n and then decreases ; 2 n will be the number of iterations | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int mat [ ] [ 4 ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int n = 4 , mode = 0 , it = 0 , lower = 0 ; for ( int t = 0 ; t < ( 2 * n - 1 ) ; t ++ ) { int t1 = t ; if ( t1 >= n ) { mode ++ ; t1 = n - 1 ; it -- ; lower ++ ; } else { lower = 0 ; it ++ ; } for ( int i = t1 ; i >= lower ; i -- ) { if ( ( t1 + mode ) % 2 == 0 ) { cout << ( mat [ i ] [ t1 + lower - i ] ) << endl ; } else { cout << ( mat [ t1 + lower - i ] [ i ] ) << endl ; } } } return 0 ; } |
Maximum difference of sum of elements in two rows in a matrix | C ++ program to find maximum difference of sum of elements of two rows ; Function to find maximum difference of sum of elements of two rows such that second row appears before first row . ; auxiliary array to store sum of all elements of each row ; calculate sum of each row and store it in rowSum array ; calculating maximum difference of two elements such that rowSum [ i ] < rowsum [ j ] ; if current difference is greater than previous then update it ; if new element is less than previous minimum element then update it so that we may get maximum difference in remaining array ; Driver program to run the case | #include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; int maxRowDiff ( int mat [ ] [ MAX ] , int m , int n ) { int rowSum [ m ] ; for ( int i = 0 ; i < m ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) sum += mat [ i ] [ j ] ; rowSum [ i ] = sum ; } int max_diff = rowSum [ 1 ] - rowSum [ 0 ] ; int min_element = rowSum [ 0 ] ; for ( int i = 1 ; i < m ; i ++ ) { if ( rowSum [ i ] - min_element > max_diff ) max_diff = rowSum [ i ] - min_element ; if ( rowSum [ i ] < min_element ) min_element = rowSum [ i ] ; } return max_diff ; } int main ( ) { int m = 5 , n = 4 ; int mat [ ] [ MAX ] = { { -1 , 2 , 3 , 4 } , { 5 , 3 , -2 , 1 } , { 6 , 7 , 2 , -3 } , { 2 , 9 , 1 , 4 } , { 2 , 1 , -2 , 0 } } ; cout << maxRowDiff ( mat , m , n ) ; return 0 ; } |
Total coverage of all zeros in a binary matrix | C ++ program to get total coverage of all zeros in a binary matrix ; Returns total coverage of all zeros in mat [ ] [ ] ; looping for all rows of matrix ; 1 is not seen yet ; looping in columns from left to right direction to get left ones ; If one is found from left ; If 0 is found and we have found a 1 before . ; Repeat the above process for right to left direction . ; Traversing across columms for up and down directions . ; 1 is not seen yet ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 4 NEW_LINE #define C 4 NEW_LINE int getTotalCoverageOfMatrix ( int mat [ R ] [ C ] ) { int res = 0 ; for ( int i = 0 ; i < R ; i ++ ) { bool isOne = false ; for ( int j = 0 ; j < C ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) isOne = true ; else if ( isOne ) res ++ ; } isOne = false ; for ( int j = C - 1 ; j >= 0 ; j -- ) { if ( mat [ i ] [ j ] == 1 ) isOne = true ; else if ( isOne ) res ++ ; } } for ( int j = 0 ; j < C ; j ++ ) { bool isOne = false ; for ( int i = 0 ; i < R ; i ++ ) { if ( mat [ i ] [ j ] == 1 ) isOne = true ; else if ( isOne ) res ++ ; } isOne = false ; for ( int i = R - 1 ; i >= 0 ; i -- ) { if ( mat [ i ] [ j ] == 1 ) isOne = true ; else if ( isOne ) res ++ ; } } return res ; } int main ( ) { int mat [ R ] [ C ] = { { 0 , 0 , 0 , 0 } , { 1 , 0 , 0 , 1 } , { 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 0 } } ; cout << getTotalCoverageOfMatrix ( mat ) ; return 0 ; } |
Count all sorted rows in a matrix | C ++ program to find number of sorted rows ; Function to count all sorted rows in a matrix ; Initialize result ; Start from left side of matrix to count increasing order rows ; Check if there is any pair ofs element that are not in increasing order . ; If the loop didn 't break (All elements of current row were in increasing order) ; Start from right side of matrix to count increasing order rows ( reference to left these are in decreasing order ) ; Check if there is any pair ofs element that are not in decreasing order . ; Note c > 1 condition is required to make sure that a single column row is not counted twice ( Note that a single column row is sorted both in increasing and decreasing order ) ; Driver program to run the case | #include <bits/stdc++.h> NEW_LINE #define MAX 100 NEW_LINE using namespace std ; int sortedCount ( int mat [ ] [ MAX ] , int r , int c ) { int result = 0 ; for ( int i = 0 ; i < r ; i ++ ) { int j ; for ( j = 0 ; j < c - 1 ; j ++ ) if ( mat [ i ] [ j + 1 ] <= mat [ i ] [ j ] ) break ; if ( j == c - 1 ) result ++ ; } for ( int i = 0 ; i < r ; i ++ ) { int j ; for ( j = c - 1 ; j > 0 ; j -- ) if ( mat [ i ] [ j - 1 ] <= mat [ i ] [ j ] ) break ; if ( c > 1 && j == 0 ) result ++ ; } return result ; } int main ( ) { int m = 4 , n = 5 ; int mat [ ] [ MAX ] = { { 1 , 2 , 3 , 4 , 5 } , { 4 , 3 , 1 , 2 , 6 } , { 8 , 7 , 6 , 5 , 4 } , { 5 , 7 , 8 , 9 , 10 } } ; cout << sortedCount ( mat , m , n ) ; return 0 ; } |
Queries in a Matrix | C ++ implementation of program ; Fills initial values in rows [ ] and cols [ ] ; Fill rows with 1 to m - 1 ; Fill columns with 1 to n - 1 ; Function to perform queries on matrix m -- > number of rows n -- > number of columns ch -- > type of query x -- > number of row for query y -- > number of column for query ; perform queries ; swap row x with y ; swap column x with y ; Print value at ( x , y ) ; Driver program to run the case ; row [ ] is array for rows and cols [ ] is array for columns ; Fill initial values in rows [ ] and cols [ ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; void preprocessMatrix ( int rows [ ] , int cols [ ] , int m , int n ) { for ( int i = 0 ; i < m ; i ++ ) rows [ i ] = i ; for ( int i = 0 ; i < n ; i ++ ) cols [ i ] = i ; } void queryMatrix ( int rows [ ] , int cols [ ] , int m , int n , char ch , int x , int y ) { int tmp ; switch ( ch ) { case ' R ' : swap ( rows [ x - 1 ] , rows [ y - 1 ] ) ; break ; case ' C ' : swap ( cols [ x - 1 ] , cols [ y - 1 ] ) ; break ; case ' P ' : printf ( " value β at β ( % d , β % d ) β = β % d STRNEWLINE " , x , y , rows [ x - 1 ] * n + cols [ y - 1 ] + 1 ) ; break ; } return ; } int main ( ) { int m = 1234 , n = 5678 ; int rows [ m ] , cols [ n ] ; preprocessMatrix ( rows , cols , m , n ) ; queryMatrix ( rows , cols , m , n , ' R ' , 1 , 2 ) ; queryMatrix ( rows , cols , m , n , ' P ' , 1 , 1 ) ; queryMatrix ( rows , cols , m , n , ' P ' , 2 , 1 ) ; queryMatrix ( rows , cols , m , n , ' C ' , 1 , 2 ) ; queryMatrix ( rows , cols , m , n , ' P ' , 1 , 1 ) ; queryMatrix ( rows , cols , m , n , ' P ' , 2 , 1 ) ; return 0 ; } |
Maximum XOR value in matrix | C ++ program to Find maximum XOR value in matrix either row / column wise ; function return the maximum xor value that is either row or column wise ; for row xor and column xor ; traverse matrix ; xor row element ; for each column : j is act as row & i act as column xor column element ; update maximum between r_xor , c_xor ; return maximum xor value ; driver Code | #include <iostream> NEW_LINE using namespace std ; const int MAX = 1000 ; int maxXOR ( int mat [ ] [ MAX ] , int N ) { int r_xor , c_xor ; int max_xor = 0 ; for ( int i = 0 ; i < N ; i ++ ) { r_xor = 0 , c_xor = 0 ; for ( int j = 0 ; j < N ; j ++ ) { r_xor = r_xor ^ mat [ i ] [ j ] ; c_xor = c_xor ^ mat [ j ] [ i ] ; } if ( max_xor < max ( r_xor , c_xor ) ) max_xor = max ( r_xor , c_xor ) ; } return max_xor ; } int main ( ) { int N = 3 ; int mat [ ] [ MAX ] = { { 1 , 5 , 4 } , { 3 , 7 , 2 } , { 5 , 9 , 10 } } ; cout << " maximum β XOR β value β : β " << maxXOR ( mat , N ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.