text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Interchange elements of first and last rows in matrix | Python code to swap the element of first and last row and display the result ; swapping of element between first and last rows ; input in the array ; printing the interchanged matrix | def interchangeFirstLast ( mat , n , m ) : NEW_LINE INDENT rows = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT t = mat [ 0 ] [ i ] NEW_LINE mat [ 0 ] [ i ] = mat [ rows - 1 ] [ i ] NEW_LINE mat [ rows - 1 ] [ i ] = t NEW_LINE DEDENT DEDENT mat = [ [ 8 , 9 , 7 , 6 ] , [ 4 , 7 , 6 , 5 ] , [ 3 , 2 , 1 , 8 ] , [ 9 , 9 , 7 , 7 ] ] NEW_LINE n = 4 NEW_LINE m = 4 NEW_LINE interchangeFirstLast ( mat , n , m ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT |
Construct Binary Tree from given Parent Array representation | A node structure ; 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 and array created [ ] to keep track of created nodes , initialize all entries as None ; Inorder traversal of tree ; Driver Method | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def createNode ( parent , i , created , root ) : NEW_LINE INDENT if created [ i ] is not None : NEW_LINE INDENT return NEW_LINE DEDENT created [ i ] = Node ( i ) NEW_LINE if parent [ i ] == - 1 : NEW_LINE INDENT root [ 0 ] = created [ i ] NEW_LINE return NEW_LINE DEDENT if created [ parent [ i ] ] is None : NEW_LINE INDENT createNode ( parent , parent [ i ] , created , root ) NEW_LINE DEDENT p = created [ parent [ i ] ] NEW_LINE if p . left is None : NEW_LINE INDENT p . left = created [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT p . right = created [ i ] NEW_LINE DEDENT DEDENT def createTree ( parent ) : NEW_LINE INDENT n = len ( parent ) NEW_LINE created = [ None for i in range ( n + 1 ) ] NEW_LINE root = [ None ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT createNode ( parent , i , created , root ) NEW_LINE DEDENT return root [ 0 ] NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print root . key , NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT parent = [ - 1 , 0 , 0 , 1 , 1 , 3 , 5 ] NEW_LINE root = createTree ( parent ) NEW_LINE print " Inorder β Traversal β of β constructed β tree " NEW_LINE inorder ( root ) NEW_LINE |
Row wise sorting in 2D array | Python3 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 | def sortRowWise ( m ) : NEW_LINE INDENT for i in range ( len ( m ) ) : NEW_LINE INDENT for j in range ( len ( m [ i ] ) ) : NEW_LINE INDENT for k in range ( len ( m [ i ] ) - j - 1 ) : NEW_LINE INDENT if ( m [ i ] [ k ] > m [ i ] [ k + 1 ] ) : NEW_LINE INDENT t = m [ i ] [ k ] NEW_LINE m [ i ] [ k ] = m [ i ] [ k + 1 ] NEW_LINE m [ i ] [ k + 1 ] = t NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( len ( m ) ) : NEW_LINE INDENT for j in range ( len ( m [ i ] ) ) : NEW_LINE INDENT print ( m [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT m = [ [ 9 , 8 , 7 , 1 ] , [ 7 , 3 , 0 , 2 ] , [ 9 , 5 , 3 , 2 ] , [ 6 , 3 , 1 , 2 ] ] NEW_LINE sortRowWise ( m ) NEW_LINE |
Row wise sorting in 2D array | Python3 code to sort 2D matrix row - wise ; One by one sort individual rows . ; printing the sorted matrix ; Driver code | def sortRowWise ( m ) : NEW_LINE INDENT for i in range ( len ( m ) ) : NEW_LINE INDENT m [ i ] . sort ( ) NEW_LINE DEDENT for i in range ( len ( m ) ) : NEW_LINE INDENT for j in range ( len ( m [ i ] ) ) : NEW_LINE INDENT print ( m [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT return 0 NEW_LINE DEDENT m = [ [ 9 , 8 , 7 , 1 ] , [ 7 , 3 , 0 , 2 ] , [ 9 , 5 , 3 , 2 ] , [ 6 , 3 , 1 , 2 ] ] NEW_LINE sortRowWise ( m ) NEW_LINE |
Program for Markov matrix | Python 3 code to check Markov Matrix ; Outer loop to access rows and inner to access columns ; Find sum of current row ; Matrix to check ; Calls the function check ( ) | def checkMarkov ( m ) : NEW_LINE INDENT for i in range ( 0 , len ( m ) ) : NEW_LINE INDENT sm = 0 NEW_LINE for j in range ( 0 , len ( m [ i ] ) ) : NEW_LINE INDENT sm = sm + m [ i ] [ j ] NEW_LINE DEDENT if ( sm != 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT m = [ [ 0 , 0 , 1 ] , [ 0.5 , 0 , 0.5 ] , [ 1 , 0 , 0 ] ] NEW_LINE if ( checkMarkov ( m ) ) : NEW_LINE INDENT print ( " β yes β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β no β " ) NEW_LINE DEDENT |
Program to check diagonal matrix and scalar matrix | Python3 Program to check if 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 | N = 4 NEW_LINE def isDiagonalMatrix ( mat ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT if ( ( i != j ) and ( mat [ i ] [ j ] != 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT mat = [ [ 4 , 0 , 0 , 0 ] , [ 0 , 7 , 0 , 0 ] , [ 0 , 0 , 5 , 0 ] , [ 0 , 0 , 0 , 1 ] ] NEW_LINE if ( isDiagonalMatrix ( mat ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
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 | N = 4 NEW_LINE def isScalarMatrix ( mat ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT if ( ( i != j ) and ( mat [ i ] [ j ] != 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT for i in range ( 0 , N - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ i ] != mat [ i + 1 ] [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT mat = [ [ 2 , 0 , 0 , 0 ] , [ 0 , 2 , 0 , 0 ] , [ 0 , 0 , 2 , 0 ] , [ 0 , 0 , 0 , 2 ] ] NEW_LINE if ( isScalarMatrix ( mat ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Construct a Binary Tree from Postorder and Inorder | 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 | def buildUtil ( In , post , inStrt , inEnd , pIndex ) : NEW_LINE INDENT if ( inStrt > inEnd ) : NEW_LINE INDENT return None NEW_LINE DEDENT node = newNode ( post [ pIndex [ 0 ] ] ) NEW_LINE pIndex [ 0 ] -= 1 NEW_LINE if ( inStrt == inEnd ) : NEW_LINE INDENT return node NEW_LINE DEDENT iIndex = search ( In , inStrt , inEnd , node . data ) NEW_LINE node . right = buildUtil ( In , post , iIndex + 1 , inEnd , pIndex ) NEW_LINE node . left = buildUtil ( In , post , inStrt , iIndex - 1 , pIndex ) NEW_LINE return node NEW_LINE DEDENT def buildTree ( In , post , n ) : NEW_LINE INDENT pIndex = [ n - 1 ] NEW_LINE return buildUtil ( In , post , 0 , n - 1 , pIndex ) NEW_LINE DEDENT def search ( arr , strt , end , value ) : NEW_LINE INDENT i = 0 NEW_LINE for i in range ( strt , end + 1 ) : NEW_LINE INDENT if ( arr [ i ] == value ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return i NEW_LINE DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def preOrder ( node ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return NEW_LINE DEDENT print ( node . data , end = " β " ) NEW_LINE preOrder ( node . left ) NEW_LINE preOrder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT In = [ 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 ] NEW_LINE post = [ 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 ] NEW_LINE n = len ( In ) NEW_LINE root = buildTree ( In , post , n ) NEW_LINE print ( " Preorder β of β the β constructed β tree β : " ) NEW_LINE preOrder ( root ) NEW_LINE DEDENT |
Check given matrix is magic square or not | Python3 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 Code | N = 3 NEW_LINE def isMagicSquare ( mat ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT s = s + mat [ i ] [ i ] NEW_LINE DEDENT s2 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT s2 = s2 + mat [ i ] [ N - i - 1 ] NEW_LINE DEDENT if ( s != s2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT rowSum = 0 ; NEW_LINE for j in range ( 0 , N ) : NEW_LINE INDENT rowSum += mat [ i ] [ j ] NEW_LINE DEDENT if ( rowSum != s ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT colSum = 0 NEW_LINE for j in range ( 0 , N ) : NEW_LINE INDENT colSum += mat [ j ] [ i ] NEW_LINE DEDENT if ( s != colSum ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT mat = [ [ 2 , 7 , 6 ] , [ 9 , 5 , 1 ] , [ 4 , 3 , 8 ] ] NEW_LINE if ( isMagicSquare ( mat ) ) : NEW_LINE INDENT print ( " Magic β Square " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β a β magic β Square " ) NEW_LINE DEDENT |
Count sub | 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 ; 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 Code | def subCount ( arr , n , k ) : NEW_LINE INDENT mod = [ 0 ] * k ; NEW_LINE cumSum = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cumSum = cumSum + arr [ i ] ; NEW_LINE mod [ ( ( cumSum % k ) + k ) % k ] = mod [ ( ( cumSum % k ) + k ) % k ] + 1 ; NEW_LINE DEDENT result = 0 ; NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT if ( mod [ i ] > 1 ) : NEW_LINE INDENT result = result + int ( ( mod [ i ] * ( mod [ i ] - 1 ) ) / 2 ) ; NEW_LINE DEDENT DEDENT result = result + mod [ 0 ] ; NEW_LINE return result ; NEW_LINE DEDENT def countSubmatrix ( mat , n , k ) : NEW_LINE INDENT tot_count = 0 ; NEW_LINE temp = [ 0 ] * n ; NEW_LINE for left in range ( 0 , n - 1 ) : NEW_LINE INDENT for right in range ( left , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT temp [ i ] = ( temp [ i ] + mat [ i ] [ right ] ) ; NEW_LINE DEDENT tot_count = ( tot_count + subCount ( temp , n , k ) ) ; NEW_LINE DEDENT DEDENT return tot_count ; NEW_LINE DEDENT mat = [ [ 5 , - 1 , 6 ] , [ - 2 , 3 , 8 ] , [ 7 , 4 , - 9 ] ] ; NEW_LINE n = 3 ; NEW_LINE k = 4 ; NEW_LINE print ( " Count β = β { } " . format ( countSubmatrix ( mat , n , k ) ) ) ; NEW_LINE |
Minimum operations required to make each row and column of matrix equals | 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 | def findMinOpeartion ( matrix , n ) : NEW_LINE INDENT sumRow = [ 0 ] * n NEW_LINE sumCol = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT sumRow [ i ] += matrix [ i ] [ j ] NEW_LINE sumCol [ j ] += matrix [ i ] [ j ] NEW_LINE DEDENT DEDENT maxSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxSum = max ( maxSum , sumRow [ i ] ) NEW_LINE maxSum = max ( maxSum , sumCol [ i ] ) NEW_LINE DEDENT count = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while i < n and j < n : NEW_LINE INDENT diff = min ( maxSum - sumRow [ i ] , maxSum - sumCol [ j ] ) NEW_LINE matrix [ i ] [ j ] += diff NEW_LINE sumRow [ i ] += diff NEW_LINE sumCol [ j ] += diff NEW_LINE count += diff NEW_LINE if ( sumRow [ i ] == maxSum ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( sumCol [ j ] == maxSum ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def printMatrix ( matrix , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( matrix [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT matrix = [ [ 1 , 2 ] , [ 3 , 4 ] ] NEW_LINE print ( findMinOpeartion ( matrix , 2 ) ) NEW_LINE printMatrix ( matrix , 2 ) NEW_LINE DEDENT |
Count frequency of k in a matrix of size n where matrix ( i , j ) = i + j | Python program to find the frequency of k in matrix where m ( i , j ) = i + j ; Driver Code | import math NEW_LINE def find ( n , k ) : NEW_LINE INDENT if ( n + 1 >= k ) : NEW_LINE INDENT return ( k - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( 2 * n + 1 - k ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE k = 7 NEW_LINE freq = find ( n , k ) NEW_LINE if ( freq < 0 ) : NEW_LINE INDENT print ( " β element β not β exist " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β Frequency β of β " , k , " β is β " , freq ) NEW_LINE DEDENT |
Given 1 ' s , β 2' s , 3 ' s β . . . . . . k ' s print them 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 | def ZigZag ( rows , columns , numbers ) : NEW_LINE INDENT k = 0 NEW_LINE arr = [ [ 0 for i in range ( columns ) ] for j in range ( rows ) ] NEW_LINE for i in range ( rows ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT j = 0 NEW_LINE while j < columns and numbers [ k ] > 0 : NEW_LINE INDENT arr [ i ] [ j ] = k + 1 NEW_LINE numbers [ k ] -= 1 NEW_LINE if numbers [ k ] == 0 : NEW_LINE INDENT k += 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT j = columns - 1 NEW_LINE while j >= 0 and numbers [ k ] > 0 : NEW_LINE INDENT arr [ i ] [ j ] = k + 1 NEW_LINE numbers [ k ] -= 1 NEW_LINE if numbers [ k ] == 0 : NEW_LINE INDENT k += 1 NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT DEDENT DEDENT for i in arr : NEW_LINE INDENT for j in i : NEW_LINE INDENT print ( j , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT rows = 4 ; NEW_LINE columns = 5 ; NEW_LINE Numbers = [ 3 , 4 , 2 , 2 , 3 , 1 , 5 ] NEW_LINE ZigZag ( rows , columns , Numbers ) NEW_LINE |
Maximum product of 4 adjacent elements in matrix | Python3 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 | n = 5 NEW_LINE def FindMaxProduct ( arr , n ) : NEW_LINE INDENT max = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( j - 3 ) >= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i ] [ j - 1 ] * arr [ i ] [ j - 2 ] * arr [ i ] [ j - 3 ] ) NEW_LINE if ( max < result ) : NEW_LINE INDENT max = result NEW_LINE DEDENT DEDENT if ( ( i - 3 ) >= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i - 1 ] [ j ] * arr [ i - 2 ] [ j ] * arr [ i - 3 ] [ j ] ) NEW_LINE if ( max < result ) : NEW_LINE INDENT max = result NEW_LINE DEDENT DEDENT if ( ( i - 3 ) >= 0 and ( j - 3 ) >= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i - 1 ] [ j - 1 ] * arr [ i - 2 ] [ j - 2 ] * arr [ i - 3 ] [ j - 3 ] ) NEW_LINE if ( max < result ) : NEW_LINE INDENT max = result NEW_LINE DEDENT DEDENT if ( ( i - 3 ) >= 0 and ( j - 1 ) <= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i - 1 ] [ j + 1 ] * arr [ i - 2 ] [ j + 2 ] * arr [ i - 3 ] [ j + 3 ] ) NEW_LINE if ( max < result ) : NEW_LINE INDENT max = result NEW_LINE DEDENT DEDENT DEDENT DEDENT return max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 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 ] ] NEW_LINE print ( FindMaxProduct ( arr , n ) ) NEW_LINE DEDENT |
Construct a Binary Tree from Postorder and Inorder | A binary tree node has data , pointer to left child and a pointer to right child ; 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 finnd the inndex of this node inn Inorder traversal ; Using inndex inn 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 ; This funtcion is here just to test ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def buildUtil ( inn , post , innStrt , innEnd ) : NEW_LINE INDENT global mp , index NEW_LINE if ( innStrt > innEnd ) : NEW_LINE INDENT return None NEW_LINE DEDENT curr = post [ index ] NEW_LINE node = Node ( curr ) NEW_LINE index -= 1 NEW_LINE if ( innStrt == innEnd ) : NEW_LINE INDENT return node NEW_LINE DEDENT iIndex = mp [ curr ] NEW_LINE node . right = buildUtil ( inn , post , iIndex + 1 , innEnd ) NEW_LINE node . left = buildUtil ( inn , post , innStrt , iIndex - 1 ) NEW_LINE return node NEW_LINE DEDENT def buildTree ( inn , post , lenn ) : NEW_LINE INDENT global index NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT mp [ inn [ i ] ] = i NEW_LINE DEDENT index = lenn - 1 NEW_LINE return buildUtil ( inn , post , 0 , lenn - 1 ) NEW_LINE DEDENT def preOrder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( node . data , end = " β " ) NEW_LINE preOrder ( node . left ) NEW_LINE preOrder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT inn = [ 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 ] NEW_LINE post = [ 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 ] NEW_LINE n = len ( inn ) NEW_LINE mp , index = { } , 0 NEW_LINE root = buildTree ( inn , post , n ) NEW_LINE print ( " Preorder β of β the β constructed β tree β : " ) NEW_LINE preOrder ( root ) NEW_LINE DEDENT |
Minimum flip required to make Binary Matrix symmetric | Python3 code 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 | N = 3 NEW_LINE def minimumflip ( mat , n ) : NEW_LINE INDENT transpose = [ [ 0 ] * n ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT transpose [ i ] [ j ] = mat [ j ] [ i ] NEW_LINE DEDENT DEDENT flip = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if transpose [ i ] [ j ] != mat [ i ] [ j ] : NEW_LINE INDENT flip += 1 NEW_LINE DEDENT DEDENT DEDENT return int ( flip / 2 ) NEW_LINE DEDENT n = 3 NEW_LINE mat = [ [ 0 , 0 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 0 , 0 ] ] NEW_LINE print ( minimumflip ( mat , n ) ) NEW_LINE |
Minimum flip required to make Binary Matrix symmetric | Python3 code 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 | N = 3 NEW_LINE def minimumflip ( mat , n ) : NEW_LINE INDENT flip = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if mat [ i ] [ j ] != mat [ j ] [ i ] : NEW_LINE INDENT flip += 1 NEW_LINE DEDENT DEDENT DEDENT return flip NEW_LINE DEDENT n = 3 NEW_LINE mat = [ [ 0 , 0 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 0 , 0 ] ] NEW_LINE print ( minimumflip ( mat , n ) ) NEW_LINE |
Frequencies of even and odd numbers in a matrix | Python 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 | MAX = 100 NEW_LINE def freq ( ar , m , n ) : NEW_LINE INDENT even = 0 NEW_LINE odd = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( ar [ i ] [ j ] % 2 ) == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT DEDENT print ( " β Frequency β of β odd β number β = " , odd ) NEW_LINE print ( " β Frequency β of β even β number β = " , even ) NEW_LINE DEDENT m = 3 NEW_LINE n = 3 NEW_LINE array = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE freq ( array , m , n ) NEW_LINE |
Center element of matrix equals sums of half diagonals | Python 3 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 | MAX = 100 NEW_LINE def HalfDiagonalSums ( mat , n ) : NEW_LINE INDENT diag1_left = 0 NEW_LINE diag1_right = 0 NEW_LINE diag2_left = 0 NEW_LINE diag2_right = 0 NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while i < n : NEW_LINE INDENT if ( i < n // 2 ) : NEW_LINE INDENT diag1_left += mat [ i ] [ i ] NEW_LINE diag2_left += mat [ j ] [ i ] NEW_LINE DEDENT elif ( i > n // 2 ) : NEW_LINE INDENT diag1_right += mat [ i ] [ i ] NEW_LINE diag2_right += mat [ j ] [ i ] NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return ( diag1_left == diag2_right and diag2_right == diag2_left and diag1_right == diag2_left and diag2_right == mat [ n // 2 ] [ n // 2 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ [ 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 ] ] NEW_LINE print ( " Yes " ) if ( HalfDiagonalSums ( a , 5 ) ) else print ( " No " ) NEW_LINE DEDENT |
Program for Identity Matrix | Python code to print identity matrix Function to print identity matrix ; Here end is used to stay in same line ; Driver Code | def Identity ( size ) : NEW_LINE INDENT for row in range ( 0 , size ) : NEW_LINE INDENT for col in range ( 0 , size ) : NEW_LINE INDENT if ( row == col ) : NEW_LINE INDENT print ( "1 β " , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0 β " , end = " β " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT size = 5 NEW_LINE Identity ( size ) NEW_LINE |
Program for Identity Matrix | Python3 program to check if a given matrix is identity ; Driver Code | MAX = 100 ; NEW_LINE def isIdentity ( mat , N ) : NEW_LINE INDENT for row in range ( N ) : NEW_LINE INDENT for col in range ( N ) : NEW_LINE INDENT if ( row == col and mat [ row ] [ col ] != 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT elif ( row != col and mat [ row ] [ col ] != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT DEDENT return True ; NEW_LINE DEDENT N = 4 ; NEW_LINE mat = [ [ 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 1 ] ] ; NEW_LINE if ( isIdentity ( mat , N ) ) : NEW_LINE INDENT print ( " Yes β " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No β " ) ; NEW_LINE DEDENT |
Ways of filling matrix such that product of all rows and all columns are equal to unity | 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 Code | def modPower ( a , t ) : NEW_LINE INDENT now = a ; NEW_LINE ret = 1 ; NEW_LINE mod = 100000007 ; NEW_LINE while ( t ) : NEW_LINE INDENT if ( t & 1 ) : NEW_LINE INDENT ret = now * ( ret % mod ) ; NEW_LINE DEDENT now = now * ( now % mod ) ; NEW_LINE t >>= 1 ; NEW_LINE DEDENT return ret ; NEW_LINE DEDENT def countWays ( n , m , k ) : NEW_LINE INDENT mod = 100000007 ; NEW_LINE if ( k == - 1 and ( ( n + m ) % 2 == 1 ) ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n == 1 or m == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return ( modPower ( modPower ( 2 , n - 1 ) , m - 1 ) % mod ) ; NEW_LINE DEDENT n = 2 ; NEW_LINE m = 7 ; NEW_LINE k = 1 ; NEW_LINE print ( countWays ( n , m , k ) ) ; NEW_LINE |
Mirror of matrix across diagonal | Simple Python3 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 pra matrix ; Driver code | MAX = 100 NEW_LINE def imageSwap ( mat , n ) : NEW_LINE INDENT row = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT s = [ ] NEW_LINE i = row NEW_LINE k = j NEW_LINE while ( i < n and k >= 0 ) : NEW_LINE INDENT s . append ( mat [ i ] [ k ] ) NEW_LINE i += 1 NEW_LINE k -= 1 NEW_LINE DEDENT i = row NEW_LINE k = j NEW_LINE while ( i < n and k >= 0 ) : NEW_LINE INDENT mat [ i ] [ k ] = s [ - 1 ] NEW_LINE k -= 1 NEW_LINE i += 1 NEW_LINE s . pop ( ) NEW_LINE DEDENT DEDENT column = n - 1 NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT s = [ ] NEW_LINE i = j NEW_LINE k = column NEW_LINE while ( i < n and k >= 0 ) : NEW_LINE INDENT s . append ( mat [ i ] [ k ] ) NEW_LINE i += 1 NEW_LINE k -= 1 NEW_LINE DEDENT i = j NEW_LINE k = column NEW_LINE while ( i < n and k >= 0 ) : NEW_LINE INDENT mat [ i ] [ k ] = s [ - 1 ] NEW_LINE i += 1 NEW_LINE k -= 1 NEW_LINE s . pop ( ) NEW_LINE DEDENT DEDENT DEDENT def printMatrix ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE n = 4 NEW_LINE imageSwap ( mat , n ) NEW_LINE printMatrix ( mat , n ) NEW_LINE |
Mirror of matrix across diagonal | Efficient Python3 program to find mirror of matrix across diagonal . ; traverse a matrix and swap mat [ i ] [ j ] with mat [ j ] [ i ] ; Utility function to pra matrix ; Driver code | from builtins import range NEW_LINE MAX = 100 ; NEW_LINE def imageSwap ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT t = mat [ i ] [ j ] ; NEW_LINE mat [ i ] [ j ] = mat [ j ] [ i ] NEW_LINE mat [ j ] [ i ] = t NEW_LINE DEDENT DEDENT DEDENT def printMatrix ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ; NEW_LINE n = 4 ; NEW_LINE imageSwap ( mat , n ) ; NEW_LINE printMatrix ( mat , n ) ; NEW_LINE DEDENT |
Find all rectangles filled with 0 | Python program to find all rectangles filled with 0 ; 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 | def findend ( i , j , a , output , index ) : NEW_LINE INDENT x = len ( a ) NEW_LINE y = len ( a [ 0 ] ) NEW_LINE flagc = 0 NEW_LINE flagr = 0 NEW_LINE for m in range ( i , x ) : NEW_LINE INDENT if a [ m ] [ j ] == 1 : NEW_LINE INDENT flagr = 1 NEW_LINE break NEW_LINE DEDENT if a [ m ] [ j ] == 5 : NEW_LINE INDENT pass NEW_LINE DEDENT for n in range ( j , y ) : NEW_LINE INDENT if a [ m ] [ n ] == 1 : NEW_LINE INDENT flagc = 1 NEW_LINE break NEW_LINE DEDENT a [ m ] [ n ] = 5 NEW_LINE DEDENT DEDENT if flagr == 1 : NEW_LINE INDENT output [ index ] . append ( m - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT output [ index ] . append ( m ) NEW_LINE DEDENT if flagc == 1 : NEW_LINE INDENT output [ index ] . append ( n - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT output [ index ] . append ( n ) NEW_LINE DEDENT DEDENT def get_rectangle_coordinates ( a ) : NEW_LINE INDENT size_of_array = len ( a ) NEW_LINE output = [ ] NEW_LINE index = - 1 NEW_LINE for i in range ( 0 , size_of_array ) : NEW_LINE INDENT for j in range ( 0 , len ( a [ 0 ] ) ) : NEW_LINE INDENT if a [ i ] [ j ] == 0 : NEW_LINE INDENT output . append ( [ i , j ] ) NEW_LINE index = index + 1 NEW_LINE findend ( i , j , a , output , index ) NEW_LINE DEDENT DEDENT DEDENT print ( output ) NEW_LINE DEDENT 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 ] ] NEW_LINE get_rectangle_coordinates ( tests ) NEW_LINE |
Search in a 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 | def search ( mat , n , x ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == x ) : NEW_LINE INDENT print ( " Element β found β at β ( " , i , " , " , j , " ) " ) NEW_LINE return 1 NEW_LINE DEDENT DEDENT DEDENT print ( " β Element β not β found " ) NEW_LINE return 0 NEW_LINE DEDENT mat = [ [ 10 , 20 , 30 , 40 ] , [ 15 , 25 , 35 , 45 ] , [ 27 , 29 , 37 , 48 ] , [ 32 , 33 , 39 , 50 ] ] NEW_LINE search ( mat , 4 , 29 ) NEW_LINE |
Search in a 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 ; if mat [ i ] [ j ] < x ; if ( i == n j == - 1 ) ; Driver Code | def search ( mat , n , x ) : NEW_LINE INDENT i = 0 NEW_LINE j = n - 1 NEW_LINE while ( i < n and j >= 0 ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == x ) : NEW_LINE INDENT print ( " n β Found β at β " , i , " , β " , j ) NEW_LINE return 1 NEW_LINE DEDENT if ( mat [ i ] [ j ] > x ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT print ( " Element β not β found " ) NEW_LINE return 0 NEW_LINE DEDENT mat = [ [ 10 , 20 , 30 , 40 ] , [ 15 , 25 , 35 , 45 ] , [ 27 , 29 , 37 , 48 ] , [ 32 , 33 , 39 , 50 ] ] NEW_LINE search ( mat , 4 , 29 ) NEW_LINE |
Create a matrix with alternating rectangles of O and X | Function to pralternating rectangles of 0 and X ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Store given number of rows and columns for later use ; A 2D array to store the output to be printed ; Iniitialize the character to be stoed in a [ ] [ ] ; Fill characters in a [ ] [ ] in spiral form . Every iteration fills one rectangle of either Xs or Os ; Fill the first row from the remaining rows ; Fill the last column from the remaining columns ; Fill the last row from the remaining rows ; Print the first column from the remaining columns ; Flip character for next iteration ; Print the filled matrix ; Driver Code | def fill0X ( m , n ) : NEW_LINE INDENT i , k , l = 0 , 0 , 0 NEW_LINE r = m NEW_LINE c = n NEW_LINE a = [ [ None ] * n for i in range ( m ) ] NEW_LINE x = ' X ' NEW_LINE while k < m and l < n : NEW_LINE INDENT for i in range ( l , n ) : NEW_LINE INDENT a [ k ] [ i ] = x NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , m ) : NEW_LINE INDENT a [ i ] [ n - 1 ] = x NEW_LINE DEDENT n -= 1 NEW_LINE if k < m : NEW_LINE INDENT for i in range ( n - 1 , l - 1 , - 1 ) : NEW_LINE INDENT a [ m - 1 ] [ i ] = x NEW_LINE DEDENT m -= 1 NEW_LINE DEDENT if l < n : NEW_LINE INDENT for i in range ( m - 1 , k - 1 , - 1 ) : NEW_LINE INDENT a [ i ] [ l ] = x NEW_LINE DEDENT l += 1 NEW_LINE DEDENT x = ' X ' if x == '0' else '0' NEW_LINE DEDENT for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT print ( a [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( " Output β for β m β = β 5 , β n β = β 6" ) NEW_LINE fill0X ( 5 , 6 ) NEW_LINE print ( " Output β for β m β = β 4 , β n β = β 4" ) NEW_LINE fill0X ( 4 , 4 ) NEW_LINE print ( " Output β for β m β = β 3 , β n β = β 4" ) NEW_LINE fill0X ( 3 , 4 ) NEW_LINE DEDENT |
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 | R = 5 NEW_LINE C = 5 NEW_LINE def diagonalOrder ( arr , n , m ) : NEW_LINE INDENT ans = [ [ ] for i in range ( n + m - 1 ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT ans [ i + j ] . append ( arr [ j ] [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT for j in range ( len ( ans [ i ] ) ) : NEW_LINE INDENT print ( ans [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE m = 4 NEW_LINE arr = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] , [ 17 , 18 , 19 , 20 ] ] NEW_LINE diagonalOrder ( arr , n , m ) NEW_LINE |
Minimum cost to sort a matrix of numbers from 0 to n ^ 2 | 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 | n = 4 NEW_LINE def calculateEnergy ( mat , n ) : NEW_LINE INDENT tot_energy = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT q = mat [ i ] [ j ] // n NEW_LINE i_des = q NEW_LINE j_des = mat [ i ] [ j ] - ( n * q ) NEW_LINE tot_energy += ( abs ( i_des - i ) + abs ( j_des - j ) ) NEW_LINE DEDENT DEDENT return tot_energy NEW_LINE DEDENT mat = [ [ 4 , 7 , 0 , 3 ] , [ 8 , 5 , 6 , 1 ] , [ 9 , 11 , 10 , 2 ] , [ 15 , 13 , 14 , 12 ] ] NEW_LINE print ( " Total β energy β required β = β " , calculateEnergy ( mat , n ) , " units " ) NEW_LINE |
Unique cells in a binary matrix | Python3 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 | MAX = 100 NEW_LINE def isUnique ( mat , i , j , n , m ) : NEW_LINE INDENT sumrow = 0 NEW_LINE for k in range ( m ) : NEW_LINE INDENT sumrow += mat [ i ] [ k ] NEW_LINE if ( sumrow > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT sumcol = 0 NEW_LINE for k in range ( n ) : NEW_LINE INDENT sumcol += mat [ k ] [ j ] NEW_LINE if ( sumcol > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countUnique ( mat , n , m ) : NEW_LINE INDENT uniquecount = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] and isUnique ( mat , i , j , n , m ) ) : NEW_LINE INDENT uniquecount += 1 NEW_LINE DEDENT DEDENT DEDENT return uniquecount NEW_LINE DEDENT mat = [ [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 1 , 0 , 0 , 1 ] ] NEW_LINE print ( countUnique ( mat , 3 , 4 ) ) NEW_LINE |
Unique cells in a binary matrix | Efficient Python3 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 | MAX = 100 ; NEW_LINE def countUnique ( mat , n , m ) : NEW_LINE INDENT rowsum = [ 0 ] * n ; NEW_LINE colsum = [ 0 ] * m ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != 0 ) : NEW_LINE INDENT rowsum [ i ] += 1 ; NEW_LINE colsum [ j ] += 1 ; NEW_LINE DEDENT DEDENT DEDENT uniquecount = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != 0 and rowsum [ i ] == 1 and colsum [ j ] == 1 ) : NEW_LINE INDENT uniquecount += 1 ; NEW_LINE DEDENT DEDENT DEDENT return uniquecount ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 1 , 0 , 0 , 1 ] ] ; NEW_LINE print ( countUnique ( mat , 3 , 4 ) ) ; NEW_LINE DEDENT |
Check if a given matrix is sparse or not | Python 3 code to check if a matrix is sparse . ; Count number of zeros in the matrix ; Driver Function | MAX = 100 NEW_LINE def isSparse ( array , m , n ) : NEW_LINE INDENT counter = 0 NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( array [ i ] [ j ] == 0 ) : NEW_LINE INDENT counter = counter + 1 NEW_LINE DEDENT DEDENT DEDENT return ( counter > ( ( m * n ) // 2 ) ) NEW_LINE DEDENT array = [ [ 1 , 0 , 3 ] , [ 0 , 0 , 4 ] , [ 6 , 0 , 0 ] ] NEW_LINE m = 3 NEW_LINE n = 3 NEW_LINE if ( isSparse ( array , m , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Row | Python3 program to find common elements in two diagonals . ; Returns count of row wise same elements in two diagonals of mat [ n ] [ n ] ; Driver Code | Max = 100 NEW_LINE def countCommon ( mat , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if mat [ i ] [ i ] == mat [ i ] [ n - i - 1 ] : NEW_LINE INDENT res = res + 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE print ( countCommon ( mat , 3 ) ) NEW_LINE |
Check if sums of i | Python3 program to check the if sum of a row is same as corresponding column ; Function to check the if sum of a row is same as corresponding column ; number of rows ; number of columns | MAX = 100 ; NEW_LINE def areSumSame ( a , n , m ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for j in range ( 0 , m ) : NEW_LINE INDENT sum1 += a [ i ] [ j ] NEW_LINE sum2 += a [ j ] [ i ] NEW_LINE DEDENT if ( sum1 == sum2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT n = 4 ; NEW_LINE m = 4 ; NEW_LINE M = [ [ 1 , 2 , 3 , 4 ] , [ 9 , 5 , 3 , 1 ] , [ 0 , 3 , 5 , 6 ] , [ 0 , 4 , 5 , 6 ] ] NEW_LINE print ( areSumSame ( M , n , m ) ) NEW_LINE |
Creating a tree with Left | 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 | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . Next = self . child = None NEW_LINE self . data = data NEW_LINE DEDENT DEDENT def addSibling ( n , data ) : NEW_LINE INDENT if ( n == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT while ( n . Next ) : NEW_LINE INDENT n = n . Next NEW_LINE DEDENT n . Next = newNode ( data ) NEW_LINE return n . Next NEW_LINE DEDENT def addChild ( n , data ) : NEW_LINE INDENT if ( n == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( n . child ) : NEW_LINE INDENT return addSibling ( n . child , data ) NEW_LINE DEDENT else : NEW_LINE INDENT n . child = newNode ( data ) NEW_LINE return n . child NEW_LINE DEDENT DEDENT def traverseTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT while ( root ) : NEW_LINE INDENT print ( root . data , end = " β " ) NEW_LINE if ( root . child ) : NEW_LINE INDENT traverseTree ( root . child ) NEW_LINE DEDENT root = root . Next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE n1 = addChild ( root , 2 ) NEW_LINE n2 = addChild ( root , 3 ) NEW_LINE n3 = addChild ( root , 4 ) NEW_LINE n4 = addChild ( n3 , 6 ) NEW_LINE n5 = addChild ( root , 5 ) NEW_LINE n6 = addChild ( n5 , 7 ) NEW_LINE n7 = addChild ( n5 , 8 ) NEW_LINE n8 = addChild ( n5 , 9 ) NEW_LINE traverseTree ( root ) NEW_LINE DEDENT |
Find row number of a binary matrix having maximum number of 1 s | python 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 | N = 4 NEW_LINE def findMax ( arr ) : NEW_LINE INDENT row = 0 NEW_LINE j = N - 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT while ( arr [ i ] [ j ] == 1 and j >= 0 ) : NEW_LINE INDENT row = i NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT print ( " Row β number β = β " , row + 1 , " , β MaxCount β = β " , N - 1 - j ) NEW_LINE DEDENT arr = [ [ 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 1 , 1 , 1 ] ] NEW_LINE findMax ( arr ) NEW_LINE |
Program to Print Matrix in Z form | Python3 program to pra square matrix in Z form ; Driver code | def diag ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT elif ( i == j ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT elif ( i == n - 1 ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ [ 4 , 5 , 6 , 8 ] , [ 1 , 2 , 3 , 1 ] , [ 7 , 8 , 9 , 4 ] , [ 1 , 8 , 7 , 5 ] ] NEW_LINE diag ( a , 4 ) NEW_LINE DEDENT |
Print all palindromic paths from top left to bottom right in a matrix | Python 3 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 the path used is palindrome or not . ; Driver code | def isPalin ( str ) : NEW_LINE INDENT l = len ( str ) // 2 NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( str [ i ] != str [ len ( str ) - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def palindromicPath ( str , a , i , j , m , n ) : NEW_LINE INDENT if ( j < m - 1 or i < n - 1 ) : NEW_LINE INDENT if ( i < n - 1 ) : NEW_LINE INDENT palindromicPath ( str + a [ i ] [ j ] , a , i + 1 , j , m , n ) NEW_LINE DEDENT if ( j < m - 1 ) : NEW_LINE INDENT palindromicPath ( str + a [ i ] [ j ] , a , i , j + 1 , m , n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT str = str + a [ n - 1 ] [ m - 1 ] NEW_LINE if isPalin ( str ) : NEW_LINE INDENT print ( str ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ ' a ' , ' a ' , ' a ' , ' b ' ] , [ ' b ' , ' a ' , ' a ' , ' a ' ] , [ ' a ' , ' b ' , ' b ' , ' a ' ] ] NEW_LINE str = " " NEW_LINE palindromicPath ( str , arr , 0 , 0 , 4 , 3 ) NEW_LINE DEDENT |
Possible moves of knight | Python3 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 code | n = 4 ; NEW_LINE m = 4 ; NEW_LINE def findPossibleMoves ( mat , p , q ) : NEW_LINE INDENT global n , m ; NEW_LINE X = [ 2 , 1 , - 1 , - 2 , - 2 , - 1 , 1 , 2 ] ; NEW_LINE Y = [ 1 , 2 , 2 , 1 , - 1 , - 2 , - 2 , - 1 ] ; NEW_LINE count = 0 ; NEW_LINE for i in range ( 8 ) : NEW_LINE INDENT x = p + X [ i ] ; NEW_LINE y = q + Y [ i ] ; NEW_LINE if ( x >= 0 and y >= 0 and x < n and y < m and mat [ x ] [ y ] == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 1 ] , [ 1 , 1 , 0 , 1 ] , [ 0 , 1 , 1 , 1 ] ] ; NEW_LINE p , q = 2 , 2 ; NEW_LINE print ( findPossibleMoves ( mat , p , q ) ) ; NEW_LINE DEDENT |
Efficiently compute sums of diagonals of a matrix | A simple Python program to find sum of diagonals ; Condition for principal diagonal ; Condition for secondary diagonal ; Driver code | MAX = 100 NEW_LINE def printDiagonalSums ( mat , n ) : NEW_LINE INDENT principal = 0 NEW_LINE secondary = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT principal += mat [ i ] [ j ] NEW_LINE DEDENT if ( ( i + j ) == ( n - 1 ) ) : NEW_LINE INDENT secondary += mat [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT print ( " Principal β Diagonal : " , principal ) NEW_LINE print ( " Secondary β Diagonal : " , secondary ) NEW_LINE DEDENT a = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] NEW_LINE printDiagonalSums ( a , 4 ) NEW_LINE |
Efficiently compute sums of diagonals of a matrix | A simple Python3 program to find sum of diagonals ; Driver code | MAX = 100 NEW_LINE def printDiagonalSums ( mat , n ) : NEW_LINE INDENT principal = 0 NEW_LINE secondary = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT principal += mat [ i ] [ i ] NEW_LINE secondary += mat [ i ] [ n - i - 1 ] NEW_LINE DEDENT print ( " Principal β Diagonal : " , principal ) NEW_LINE print ( " Secondary β Diagonal : " , secondary ) NEW_LINE DEDENT a = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] NEW_LINE printDiagonalSums ( a , 4 ) NEW_LINE |
Creating a tree with Left | Python3 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 | from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE self . child = None NEW_LINE DEDENT DEDENT def addSibling ( n , data ) : NEW_LINE INDENT if ( n == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT while ( n . next ) : NEW_LINE INDENT n = n . next NEW_LINE DEDENT n . next = Node ( data ) NEW_LINE return n NEW_LINE DEDENT def addChild ( n , data ) : NEW_LINE INDENT if ( n == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( n . child ) : NEW_LINE INDENT return addSibling ( n . child , data ) NEW_LINE DEDENT else : NEW_LINE INDENT n . child = Node ( data ) NEW_LINE return n NEW_LINE DEDENT DEDENT def traverseTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( root . data , end = " β " ) NEW_LINE if ( root . child == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = deque ( ) NEW_LINE curr = root . child NEW_LINE q . append ( curr ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT curr = q . popleft ( ) NEW_LINE while ( curr != None ) : NEW_LINE INDENT print ( curr . data , end = " β " ) NEW_LINE if ( curr . child != None ) : NEW_LINE INDENT q . append ( curr . child ) NEW_LINE DEDENT curr = curr . next NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 10 ) NEW_LINE n1 = addChild ( root , 2 ) NEW_LINE n2 = addChild ( root , 3 ) NEW_LINE n3 = addChild ( root , 4 ) NEW_LINE n4 = addChild ( n3 , 6 ) NEW_LINE n5 = addChild ( root , 5 ) NEW_LINE n6 = addChild ( n5 , 7 ) NEW_LINE n7 = addChild ( n5 , 8 ) NEW_LINE n8 = addChild ( n5 , 9 ) NEW_LINE traverseTree ( root ) NEW_LINE DEDENT |
Boundary elements of a Matrix | Python program to print boundary element of the matrix . ; Driver code | MAX = 100 NEW_LINE def printBoundary ( a , m , n ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT print a [ i ] [ j ] , NEW_LINE DEDENT elif ( i == m - 1 ) : NEW_LINE INDENT print a [ i ] [ j ] , NEW_LINE DEDENT elif ( j == 0 ) : NEW_LINE INDENT print a [ i ] [ j ] , NEW_LINE DEDENT elif ( j == n - 1 ) : NEW_LINE INDENT print a [ i ] [ j ] , NEW_LINE DEDENT else : NEW_LINE INDENT print " β " , NEW_LINE DEDENT DEDENT print NEW_LINE DEDENT DEDENT a = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] NEW_LINE printBoundary ( a , 4 , 4 ) NEW_LINE |
Boundary elements of a Matrix | Python program to print boundary element of the matrix . ; Driver code | MAX = 100 NEW_LINE def printBoundary ( a , m , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT sum += a [ i ] [ j ] NEW_LINE DEDENT elif ( i == m - 1 ) : NEW_LINE INDENT sum += a [ i ] [ j ] NEW_LINE DEDENT elif ( j == 0 ) : NEW_LINE INDENT sum += a [ i ] [ j ] NEW_LINE DEDENT elif ( j == n - 1 ) : NEW_LINE INDENT sum += a [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return sum NEW_LINE DEDENT a = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] ] NEW_LINE sum = printBoundary ( a , 4 , 4 ) NEW_LINE print " Sum β of β boundary β elements β is " , sum NEW_LINE |
Print a matrix in a spiral form starting from a point | Python3 program to print a matrix in spiral form . ; Driver code ; Function calling | MAX = 100 NEW_LINE def printSpiral ( mat , r , c ) : NEW_LINE INDENT a = 0 NEW_LINE b = 2 NEW_LINE low_row = 0 if ( 0 > a ) else a NEW_LINE low_column = 0 if ( 0 > b ) else b - 1 NEW_LINE high_row = r - 1 if ( ( a + 1 ) >= r ) else a + 1 NEW_LINE high_column = c - 1 if ( ( b + 1 ) >= c ) else b + 1 NEW_LINE while ( ( low_row > 0 - r and low_column > 0 - c ) ) : NEW_LINE INDENT i = low_column + 1 NEW_LINE while ( i <= high_column and i < c and low_row >= 0 ) : NEW_LINE INDENT print ( mat [ low_row ] [ i ] , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT low_row -= 1 NEW_LINE i = low_row + 2 NEW_LINE while ( i <= high_row and i < r and high_column < c ) : NEW_LINE INDENT print ( mat [ i ] [ high_column ] , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT high_column += 1 NEW_LINE i = high_column - 2 NEW_LINE while ( i >= low_column and i >= 0 and high_row < r ) : NEW_LINE INDENT print ( mat [ high_row ] [ i ] , end = " β " ) NEW_LINE i -= 1 NEW_LINE DEDENT high_row += 1 NEW_LINE i = high_row - 2 NEW_LINE while ( i > low_row and i >= 0 and low_column >= 0 ) : NEW_LINE INDENT print ( mat [ i ] [ low_column ] , end = " β " ) NEW_LINE i -= 1 NEW_LINE DEDENT low_column -= 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE r = 3 NEW_LINE c = 3 NEW_LINE printSpiral ( mat , r , c ) NEW_LINE DEDENT |
Program to Interchange Diagonals of Matrix | Python program to interchange the diagonals of matrix ; Function to interchange diagonals ; swap elements of diagonal ; Driver Code | N = 3 ; NEW_LINE def interchangeDiagonals ( array ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( i != N / 2 ) : NEW_LINE INDENT temp = array [ i ] [ i ] ; NEW_LINE array [ i ] [ i ] = array [ i ] [ N - i - 1 ] ; NEW_LINE array [ i ] [ N - i - 1 ] = temp ; NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( array [ i ] [ j ] , end = " β " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT array = [ 4 , 5 , 6 ] , [ 1 , 2 , 3 ] , [ 7 , 8 , 9 ] ; NEW_LINE interchangeDiagonals ( array ) ; NEW_LINE DEDENT |
Find difference between sums of two diagonals | Python3 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 ; Driver Code | def difference ( arr , n ) : NEW_LINE INDENT d1 = 0 NEW_LINE d2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT d1 += arr [ i ] [ j ] NEW_LINE DEDENT if ( i == n - j - 1 ) : NEW_LINE INDENT d2 += arr [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return abs ( d1 - d2 ) ; NEW_LINE DEDENT n = 3 NEW_LINE arr = [ [ 11 , 2 , 4 ] , [ 4 , 5 , 6 ] , [ 10 , 8 , - 12 ] ] NEW_LINE print ( difference ( arr , n ) ) NEW_LINE |
Find difference between sums of two diagonals | Python3 program to find the difference between the sum of diagonal . ; Initialize sums of diagonals ; Absolute difference of the sums across the diagonals ; Driver Code | def difference ( arr , n ) : NEW_LINE INDENT d1 = 0 NEW_LINE d2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT d1 = d1 + arr [ i ] [ i ] NEW_LINE d2 = d2 + arr [ i ] [ n - i - 1 ] NEW_LINE DEDENT return abs ( d1 - d2 ) NEW_LINE DEDENT n = 3 NEW_LINE arr = [ [ 11 , 2 , 4 ] , [ 4 , 5 , 6 ] , [ 10 , 8 , - 12 ] ] NEW_LINE print ( difference ( arr , n ) ) NEW_LINE |
Circular Matrix ( Construct a matrix with numbers 1 to m * n in spiral way ) | 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 | def spiralFill ( m , n , a ) : NEW_LINE INDENT val = 1 NEW_LINE k , l = 0 , 0 NEW_LINE while ( k < m and l < n ) : NEW_LINE INDENT for i in range ( l , n ) : NEW_LINE INDENT a [ k ] [ i ] = val NEW_LINE val += 1 NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , m ) : NEW_LINE INDENT a [ i ] [ n - 1 ] = val NEW_LINE val += 1 NEW_LINE DEDENT n -= 1 NEW_LINE if ( k < m ) : NEW_LINE INDENT for i in range ( n - 1 , l - 1 , - 1 ) : NEW_LINE INDENT a [ m - 1 ] [ i ] = val NEW_LINE val += 1 NEW_LINE DEDENT m -= 1 NEW_LINE DEDENT if ( l < n ) : NEW_LINE INDENT for i in range ( m - 1 , k - 1 , - 1 ) : NEW_LINE INDENT a [ i ] [ l ] = val NEW_LINE val += 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m , n = 4 , 4 NEW_LINE a = [ [ 0 for j in range ( m ) ] for i in range ( n ) ] NEW_LINE spiralFill ( m , n , a ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( a [ i ] [ j ] , end = ' β ' ) NEW_LINE DEDENT print ( ' ' ) NEW_LINE DEDENT DEDENT |
Prufer Code to Tree Creation | 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 | def printTreeEdges ( prufer , m ) : NEW_LINE INDENT vertices = m + 2 NEW_LINE vertex_set = [ 0 ] * vertices NEW_LINE for i in range ( vertices - 2 ) : NEW_LINE INDENT vertex_set [ prufer [ i ] - 1 ] += 1 NEW_LINE DEDENT print ( " The β edge β set β E ( G ) β is β : " ) NEW_LINE j = 0 NEW_LINE for i in range ( vertices - 2 ) : NEW_LINE INDENT for j in range ( vertices ) : NEW_LINE INDENT if ( vertex_set [ j ] == 0 ) : NEW_LINE INDENT vertex_set [ j ] = - 1 NEW_LINE print ( " ( " , ( j + 1 ) , " , β " , prufer [ i ] , " ) β " , sep = " " , end = " " ) NEW_LINE vertex_set [ prufer [ i ] - 1 ] -= 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT j = 0 NEW_LINE for i in range ( vertices ) : NEW_LINE INDENT if ( vertex_set [ i ] == 0 and j == 0 ) : NEW_LINE INDENT print ( " ( " , ( i + 1 ) , " , β " , sep = " " , end = " " ) NEW_LINE j += 1 NEW_LINE DEDENT elif ( vertex_set [ i ] == 0 and j == 1 ) : NEW_LINE INDENT print ( ( i + 1 ) , " ) " ) NEW_LINE DEDENT DEDENT DEDENT prufer = [ 4 , 1 , 3 , 4 ] NEW_LINE n = len ( prufer ) NEW_LINE printTreeEdges ( prufer , n ) NEW_LINE |
Maximum and Minimum in a square matrix . | Python3 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 Code | MAX = 100 NEW_LINE def MAXMIN ( arr , n ) : NEW_LINE INDENT MIN = 10 ** 9 NEW_LINE MAX = - 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n // 2 + 1 ) : NEW_LINE INDENT if ( arr [ i ] [ j ] > arr [ i ] [ n - j - 1 ] ) : NEW_LINE INDENT if ( MIN > arr [ i ] [ n - j - 1 ] ) : NEW_LINE INDENT MIN = arr [ i ] [ n - j - 1 ] NEW_LINE DEDENT if ( MAX < arr [ i ] [ j ] ) : NEW_LINE INDENT MAX = arr [ i ] [ j ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( MIN > arr [ i ] [ j ] ) : NEW_LINE INDENT MIN = arr [ i ] [ j ] NEW_LINE DEDENT if ( MAX < arr [ i ] [ n - j - 1 ] ) : NEW_LINE INDENT MAX = arr [ i ] [ n - j - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( " MAXimum β = " , MAX , " , β MINimum β = " , MIN ) NEW_LINE DEDENT arr = [ [ 5 , 9 , 11 ] , [ 25 , 0 , 14 ] , [ 21 , 6 , 4 ] ] NEW_LINE MAXMIN ( arr , 3 ) NEW_LINE |
Print matrix in antispiral form | Python 3 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 Code | R = 4 NEW_LINE C = 5 NEW_LINE def antiSpiralTraversal ( m , n , a ) : NEW_LINE INDENT k = 0 NEW_LINE l = 0 NEW_LINE stk = [ ] NEW_LINE while ( k <= m and l <= n ) : NEW_LINE INDENT for i in range ( l , n + 1 ) : NEW_LINE INDENT stk . append ( a [ k ] [ i ] ) NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , m + 1 ) : NEW_LINE INDENT stk . append ( a [ i ] [ n ] ) NEW_LINE DEDENT n -= 1 NEW_LINE if ( k <= m ) : NEW_LINE INDENT for i in range ( n , l - 1 , - 1 ) : NEW_LINE INDENT stk . append ( a [ m ] [ i ] ) NEW_LINE DEDENT m -= 1 NEW_LINE DEDENT if ( l <= n ) : NEW_LINE INDENT for i in range ( m , k - 1 , - 1 ) : NEW_LINE INDENT stk . append ( a [ i ] [ l ] ) NEW_LINE DEDENT l += 1 NEW_LINE DEDENT DEDENT while len ( stk ) != 0 : NEW_LINE INDENT print ( str ( stk [ - 1 ] ) , end = " β " ) NEW_LINE stk . pop ( ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 10 ] , [ 11 , 12 , 13 , 14 , 15 ] , [ 16 , 17 , 18 , 19 , 20 ] ] ; NEW_LINE antiSpiralTraversal ( R - 1 , C - 1 , mat ) NEW_LINE |
Minimum operations required to set all elements 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 ; Driver Code | def minOperation ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE for k in range ( i + 1 ) : NEW_LINE INDENT for h in range ( j + 1 ) : NEW_LINE INDENT if ( arr [ k ] [ h ] == 1 ) : NEW_LINE INDENT arr [ k ] [ h ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ k ] [ h ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT mat = [ [ 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 ] ] NEW_LINE M = 5 NEW_LINE N = 5 NEW_LINE print ( minOperation ( mat ) ) NEW_LINE |
C Program To Check whether Matrix is Skew Symmetric or not | Python 3 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 | ROW = 3 NEW_LINE COL = 3 NEW_LINE def transpose ( transpose_matrix , matrix ) : NEW_LINE INDENT for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT transpose_matrix [ j ] [ i ] = matrix [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT def check ( transpose_matrix , matrix ) : NEW_LINE INDENT for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT if ( matrix [ i ] [ j ] != - transpose_matrix [ i ] [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def printMatrix ( matrix ) : NEW_LINE INDENT for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT print ( matrix [ i ] [ j ] , " β " , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT matrix = [ [ 0 , 5 , - 4 ] , [ - 5 , 0 , 1 ] , [ 4 , - 1 , 0 ] , ] NEW_LINE transpose_matrix = [ [ 0 for i in range ( 3 ) ] for j in range ( 3 ) ] NEW_LINE transpose ( transpose_matrix , matrix ) NEW_LINE print ( " Transpose β matrix : " ) NEW_LINE printMatrix ( transpose_matrix ) NEW_LINE if ( check ( transpose_matrix , matrix ) ) : NEW_LINE INDENT print ( " Skew β Symmetric β Matrix " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Skew β Symmetric β Matrix " ) NEW_LINE DEDENT |
Sum of matrix element where each elements 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 ; Driver Code | def findSum ( n ) : NEW_LINE INDENT ans = 0 ; temp = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if temp < n : NEW_LINE INDENT temp = i - 1 NEW_LINE num = 1 NEW_LINE while temp < n : NEW_LINE INDENT if temp + i <= n : NEW_LINE INDENT ans += i * num NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( n - temp ) * num NEW_LINE DEDENT temp += i NEW_LINE num += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT N = 2 NEW_LINE print ( findSum ( N ) ) NEW_LINE |
Find number of transformation to make two Matrix Equal | Python3 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 | def countOps ( A , B , m , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT A [ i ] [ j ] -= B [ i ] [ j ] ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT if ( A [ i ] [ j ] - A [ i ] [ 0 ] - A [ 0 ] [ j ] + A [ 0 ] [ 0 ] != 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT DEDENT result = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT result += abs ( A [ i ] [ 0 ] ) ; NEW_LINE DEDENT for j in range ( m ) : NEW_LINE INDENT result += abs ( A [ 0 ] [ j ] - A [ 0 ] [ 0 ] ) ; NEW_LINE DEDENT return ( result ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] ; NEW_LINE B = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; NEW_LINE print ( countOps ( A , B , 3 , 3 ) ) ; NEW_LINE DEDENT |
Construct the full k | Python3 program to build full k - ary tree from its preorder traversal and to print the postorder traversal of the tree . ; Utility function to create a new tree node with k children ; Function to build full k - ary tree ; For None 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 prpostorder traversal of the tree ; Driver Code | from math import ceil , log NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , value ) : NEW_LINE INDENT self . key = value NEW_LINE self . child = [ ] NEW_LINE DEDENT DEDENT def BuildkaryTree ( A , n , k , h , ind ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return None NEW_LINE DEDENT nNode = newNode ( A [ ind [ 0 ] ] ) NEW_LINE if ( nNode == None ) : NEW_LINE INDENT print ( " Memory β error " ) NEW_LINE return None NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT if ( ind [ 0 ] < n - 1 and h > 1 ) : NEW_LINE INDENT ind [ 0 ] += 1 NEW_LINE nNode . child . append ( BuildkaryTree ( A , n , k , h - 1 , ind ) ) NEW_LINE DEDENT else : NEW_LINE INDENT nNode . child . append ( None ) NEW_LINE DEDENT DEDENT return nNode NEW_LINE DEDENT def BuildKaryTree ( A , n , k , ind ) : NEW_LINE INDENT height = int ( ceil ( log ( float ( n ) * ( k - 1 ) + 1 ) / log ( float ( k ) ) ) ) NEW_LINE return BuildkaryTree ( A , n , k , height , ind ) NEW_LINE DEDENT def postord ( root , k ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT postord ( root . child [ i ] , k ) NEW_LINE DEDENT print ( root . key , end = " β " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ind = [ 0 ] NEW_LINE k = 3 NEW_LINE n = 10 NEW_LINE preorder = [ 1 , 2 , 5 , 6 , 7 , 3 , 8 , 9 , 10 , 4 ] NEW_LINE root = BuildKaryTree ( preorder , n , k , ind ) NEW_LINE print ( " Postorder β traversal β of β constructed " , " full β k - ary β tree β is : β " ) NEW_LINE postord ( root , k ) NEW_LINE DEDENT |
Form coils in a matrix | Prcoils 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 ; Prboth coils ; Driver code | def printCoils ( n ) : NEW_LINE INDENT m = 8 * n * n NEW_LINE coil1 = [ 0 ] * m NEW_LINE coil1 [ 0 ] = 8 * n * n + 2 * n NEW_LINE curr = coil1 [ 0 ] NEW_LINE nflg = 1 NEW_LINE step = 2 NEW_LINE index = 1 NEW_LINE while ( index < m ) : NEW_LINE INDENT for i in range ( step ) : NEW_LINE INDENT curr = coil1 [ index ] = ( curr - 4 * n * nflg ) NEW_LINE index += 1 NEW_LINE if ( index >= m ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( index >= m ) : NEW_LINE INDENT break NEW_LINE DEDENT for i in range ( step ) : NEW_LINE INDENT curr = coil1 [ index ] = curr + nflg NEW_LINE index += 1 NEW_LINE if ( index >= m ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT nflg = nflg * ( - 1 ) NEW_LINE step += 2 NEW_LINE DEDENT coil2 = [ 0 ] * m NEW_LINE i = 0 NEW_LINE while ( i < 8 * n * n ) : NEW_LINE INDENT coil2 [ i ] = 16 * n * n + 1 - coil1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT print ( " Coil β 1 β : " , end = " β " ) NEW_LINE i = 0 NEW_LINE while ( i < 8 * n * n ) : NEW_LINE INDENT print ( coil1 [ i ] , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT print ( " Coil 2 : " , β end β = β " " ) NEW_LINE i = 0 NEW_LINE while ( i < 8 * n * n ) : NEW_LINE INDENT print ( coil2 [ i ] , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT n = 1 NEW_LINE printCoils ( n ) NEW_LINE |
Sum of matrix in which each element is absolute difference of its row and column numbers | Return the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Generate matrix ; Compute sum ; Driver Code | def findSum ( n ) : NEW_LINE INDENT arr = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT arr [ i ] [ j ] = abs ( i - j ) NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT sum += arr [ i ] [ j ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( findSum ( n ) ) NEW_LINE DEDENT |
Sum of matrix in which each element is absolute difference of its row and column numbers | Return the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Driver code | def findSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += i * ( n - i ) NEW_LINE DEDENT return 2 * sum NEW_LINE DEDENT n = 3 NEW_LINE print ( findSum ( n ) ) NEW_LINE |
Sum of matrix in which each element is absolute difference of its row and column numbers | Return the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Driver Code | def findSum ( n ) : NEW_LINE INDENT n -= 1 NEW_LINE sum = 0 NEW_LINE sum += ( n * ( n + 1 ) ) / 2 NEW_LINE sum += ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 NEW_LINE return int ( sum ) NEW_LINE DEDENT n = 3 NEW_LINE print ( findSum ( n ) ) NEW_LINE |
Sum of both diagonals of a spiral odd | function returns sum of diagonals ; as order should be only odd we should pass only odd integers ; Driver program | def spiralDiaSum ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( 4 * n * n - 6 * n + 6 + spiralDiaSum ( n - 2 ) ) NEW_LINE DEDENT n = 7 ; NEW_LINE print ( spiralDiaSum ( n ) ) NEW_LINE |
Find perimeter of shapes formed with 1 s in binary matrix | Python3 program to find perimeter of area covered 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 . ; Driver Code | R = 3 NEW_LINE C = 5 NEW_LINE def numofneighbour ( mat , i , j ) : NEW_LINE INDENT count = 0 ; NEW_LINE if ( i > 0 and mat [ i - 1 ] [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( j > 0 and mat [ i ] [ j - 1 ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( i < R - 1 and mat [ i + 1 ] [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( j < C - 1 and mat [ i ] [ j + 1 ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def findperimeter ( mat ) : NEW_LINE INDENT perimeter = 0 ; NEW_LINE for i in range ( 0 , R ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_LINE INDENT if ( mat [ i ] [ j ] ) : NEW_LINE INDENT perimeter += ( 4 - numofneighbour ( mat , i , j ) ) ; NEW_LINE DEDENT DEDENT DEDENT return perimeter ; NEW_LINE DEDENT mat = [ [ 0 , 1 , 0 , 0 , 0 ] , [ 1 , 1 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 0 , 0 ] ] NEW_LINE print ( findperimeter ( mat ) , end = " " ) ; NEW_LINE |
Construct Binary Tree from String with bracket representation | Helper class that allocates a new node ; This funtcion 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 | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def preOrder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( node . data , end = " β " ) NEW_LINE preOrder ( node . left ) NEW_LINE preOrder ( node . right ) NEW_LINE DEDENT def findIndex ( Str , si , ei ) : NEW_LINE INDENT if ( si > ei ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT s = [ ] NEW_LINE for i in range ( si , ei + 1 ) : NEW_LINE INDENT if ( Str [ i ] == ' ( ' ) : NEW_LINE INDENT s . append ( Str [ i ] ) NEW_LINE DEDENT elif ( Str [ i ] == ' ) ' ) : NEW_LINE INDENT if ( s [ - 1 ] == ' ( ' ) : NEW_LINE INDENT s . pop ( - 1 ) NEW_LINE if len ( s ) == 0 : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT def treeFromString ( Str , si , ei ) : NEW_LINE INDENT if ( si > ei ) : NEW_LINE INDENT return None NEW_LINE DEDENT root = newNode ( ord ( Str [ si ] ) - ord ( '0' ) ) NEW_LINE index = - 1 NEW_LINE if ( si + 1 <= ei and Str [ si + 1 ] == ' ( ' ) : NEW_LINE INDENT index = findIndex ( Str , si + 1 , ei ) NEW_LINE DEDENT if ( index != - 1 ) : NEW_LINE INDENT root . left = treeFromString ( Str , si + 2 , index - 1 ) NEW_LINE root . right = treeFromString ( Str , index + 2 , ei - 1 ) NEW_LINE DEDENT return root NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = "4(2(3 ) ( 1 ) ) (6(5 ) ) " NEW_LINE root = treeFromString ( Str , 0 , len ( Str ) - 1 ) NEW_LINE preOrder ( root ) NEW_LINE DEDENT |
Print matrix in diagonal pattern | Python 3 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 program | MAX = 100 NEW_LINE def printMatrixDiagonal ( mat , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE isUp = True NEW_LINE while k < n * n : NEW_LINE INDENT if isUp : NEW_LINE INDENT while i >= 0 and j < n : NEW_LINE INDENT print ( str ( mat [ i ] [ j ] ) , end = " β " ) NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE i -= 1 NEW_LINE DEDENT if i < 0 and j <= n - 1 : NEW_LINE INDENT i = 0 NEW_LINE DEDENT if j == n : NEW_LINE INDENT i = i + 2 NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT while j >= 0 and i < n : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT if j < 0 and i <= n - 1 : NEW_LINE INDENT j = 0 NEW_LINE DEDENT if i == n : NEW_LINE INDENT j = j + 2 NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT isUp = not isUp NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE n = 3 NEW_LINE printMatrixDiagonal ( mat , n ) NEW_LINE DEDENT |
Print matrix in diagonal pattern | 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 | mat = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] ; NEW_LINE n = 4 NEW_LINE mode = 0 NEW_LINE it = 0 NEW_LINE lower = 0 NEW_LINE for t in range ( 2 * n - 1 ) : NEW_LINE INDENT t1 = t NEW_LINE if ( t1 >= n ) : NEW_LINE INDENT mode += 1 NEW_LINE t1 = n - 1 NEW_LINE it -= 1 NEW_LINE lower += 1 NEW_LINE DEDENT else : NEW_LINE INDENT lower = 0 NEW_LINE it += 1 NEW_LINE DEDENT for i in range ( t1 , lower - 1 , - 1 ) : NEW_LINE INDENT if ( ( t1 + mode ) % 2 == 0 ) : NEW_LINE INDENT print ( ( mat [ i ] [ t1 + lower - i ] ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( mat [ t1 + lower - i ] [ i ] ) NEW_LINE DEDENT DEDENT DEDENT |
Maximum difference of sum of elements in two rows in a matrix | 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 | def maxRowDiff ( mat , m , n ) : NEW_LINE INDENT rowSum = [ 0 ] * m NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT sum += mat [ i ] [ j ] NEW_LINE DEDENT rowSum [ i ] = sum NEW_LINE DEDENT max_diff = rowSum [ 1 ] - rowSum [ 0 ] NEW_LINE min_element = rowSum [ 0 ] NEW_LINE for i in range ( 1 , m ) : NEW_LINE INDENT if ( rowSum [ i ] - min_element > max_diff ) : NEW_LINE INDENT max_diff = rowSum [ i ] - min_element NEW_LINE DEDENT if ( rowSum [ i ] < min_element ) : NEW_LINE INDENT min_element = rowSum [ i ] NEW_LINE DEDENT DEDENT return max_diff NEW_LINE DEDENT m = 5 NEW_LINE n = 4 NEW_LINE mat = [ [ - 1 , 2 , 3 , 4 ] , [ 5 , 3 , - 2 , 1 ] , [ 6 , 7 , 2 , - 3 ] , [ 2 , 9 , 1 , 4 ] , [ 2 , 1 , - 2 , 0 ] ] NEW_LINE print ( maxRowDiff ( mat , m , n ) ) NEW_LINE |
Total coverage of all zeros in a binary matrix | Python3 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 | R = 4 NEW_LINE C = 4 NEW_LINE def getTotalCoverageOfMatrix ( mat ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( R ) : NEW_LINE INDENT isOne = False NEW_LINE for j in range ( C ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT isOne = True NEW_LINE DEDENT elif ( isOne ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT isOne = False NEW_LINE for j in range ( C - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT isOne = True NEW_LINE DEDENT elif ( isOne ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT for j in range ( C ) : NEW_LINE INDENT isOne = False NEW_LINE for i in range ( R ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT isOne = True NEW_LINE DEDENT elif ( isOne ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT isOne = False NEW_LINE for i in range ( R - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT isOne = True NEW_LINE DEDENT elif ( isOne ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT mat = [ [ 0 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 1 ] , [ 0 , 1 , 1 , 0 ] , [ 0 , 1 , 0 , 0 ] ] NEW_LINE print ( getTotalCoverageOfMatrix ( mat ) ) NEW_LINE |
Count all sorted rows in a matrix | 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 code | def sortedCount ( mat , r , c ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT j = 0 NEW_LINE for j in range ( c - 1 ) : NEW_LINE INDENT if mat [ i ] [ j + 1 ] <= mat [ i ] [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if j == c - 2 : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , r ) : NEW_LINE INDENT j = 0 NEW_LINE for j in range ( c - 1 , 0 , - 1 ) : NEW_LINE INDENT if mat [ i ] [ j - 1 ] <= mat [ i ] [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if c > 1 and j == 1 : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT m , n = 4 , 5 NEW_LINE mat = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 4 , 3 , 1 , 2 , 6 ] , [ 8 , 7 , 6 , 5 , 4 ] , [ 5 , 7 , 8 , 9 , 10 ] ] NEW_LINE print ( sortedCount ( mat , m , n ) ) NEW_LINE |
Maximum XOR value in matrix | Python3 program to Find maximum XOR value in matrix either row / column wise maximum number of row and column ; 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 | MAX = 1000 NEW_LINE def maxXOR ( mat , N ) : NEW_LINE INDENT max_xor = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT r_xor = 0 NEW_LINE c_xor = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT r_xor = r_xor ^ mat [ i ] [ j ] NEW_LINE c_xor = c_xor ^ mat [ j ] [ i ] NEW_LINE DEDENT if ( max_xor < max ( r_xor , c_xor ) ) : NEW_LINE INDENT max_xor = max ( r_xor , c_xor ) NEW_LINE DEDENT DEDENT return max_xor NEW_LINE DEDENT N = 3 NEW_LINE mat = [ [ 1 , 5 , 4 ] , [ 3 , 7 , 2 ] , [ 5 , 9 , 10 ] ] NEW_LINE print ( " maximum β XOR β value β : β " , maxXOR ( mat , N ) ) NEW_LINE |
Direction at last square block | Function which tells the Current direction ; Driver code | def direction ( R , C ) : NEW_LINE INDENT if ( R != C and R % 2 == 0 and C % 2 != 0 and R < C ) : NEW_LINE INDENT print ( " Left " ) NEW_LINE return NEW_LINE DEDENT if ( R != C and R % 2 == 0 and C % 2 == 0 and R > C ) : NEW_LINE INDENT print ( " Up " ) NEW_LINE return NEW_LINE DEDENT if R == C and R % 2 != 0 and C % 2 != 0 : NEW_LINE INDENT print ( " Right " ) NEW_LINE return NEW_LINE DEDENT if R == C and R % 2 == 0 and C % 2 == 0 : NEW_LINE INDENT print ( " Left " ) NEW_LINE return NEW_LINE DEDENT if ( R != C and R % 2 != 0 and C % 2 != 0 and R < C ) : NEW_LINE INDENT print ( " Right " ) NEW_LINE return NEW_LINE DEDENT if ( R != C and R % 2 != 0 and C % 2 != 0 and R > C ) : NEW_LINE INDENT print ( " Down " ) NEW_LINE return NEW_LINE DEDENT if ( R != C and R % 2 == 0 and C % 2 != 0 and R < C ) : NEW_LINE INDENT print ( " Left " ) NEW_LINE return NEW_LINE DEDENT if ( R != C and R % 2 == 0 and C % 2 == 0 and R > C ) : NEW_LINE INDENT print ( " Up " ) NEW_LINE return NEW_LINE DEDENT if ( R != C and R % 2 != 0 and C % 2 != 0 and R > C ) : NEW_LINE INDENT print ( " Down " ) NEW_LINE return NEW_LINE DEDENT if ( R != C and R % 2 != 0 and C % 2 != 0 and R < C ) : NEW_LINE INDENT print ( " Right " ) NEW_LINE return NEW_LINE DEDENT DEDENT R = 3 ; C = 1 NEW_LINE direction ( R , C ) NEW_LINE |
Print K 'th element in spiral form of matrix | ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; check the first row from the remaining rows ; check the last column from the remaining columns ; check the last row from the remaining rows ; check the first column from the remaining columns ; Driver program to test above functions | R = 3 NEW_LINE C = 6 NEW_LINE def spiralPrint ( m , n , a , c ) : NEW_LINE INDENT k = 0 NEW_LINE l = 0 NEW_LINE count = 0 NEW_LINE while ( k < m and l < n ) : NEW_LINE INDENT for i in range ( l , n ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == c ) : NEW_LINE INDENT print ( a [ k ] [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT k += 1 NEW_LINE for i in range ( k , m ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == c ) : NEW_LINE INDENT print ( a [ i ] [ n - 1 ] , end = " β " ) NEW_LINE DEDENT DEDENT n -= 1 NEW_LINE if ( k < m ) : NEW_LINE INDENT for i in range ( n - 1 , l - 1 , - 1 ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == c ) : NEW_LINE INDENT print ( a [ m - 1 ] [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT m -= 1 NEW_LINE DEDENT if ( l < n ) : NEW_LINE INDENT for i in range ( m - 1 , k - 1 , - 1 ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == c ) : NEW_LINE INDENT print ( a [ i ] [ l ] , end = " β " ) NEW_LINE DEDENT DEDENT l += 1 NEW_LINE DEDENT DEDENT DEDENT a = [ [ 1 , 2 , 3 , 4 , 5 , 6 ] , [ 7 , 8 , 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 , 17 , 18 ] ] NEW_LINE k = 17 NEW_LINE spiralPrint ( R , C , a , k ) NEW_LINE |
Print K 'th element in spiral form of matrix | Python3 program for Kth element in spiral form of matrix ; function for Kth element ; Element is in first row ; Element is in last column ; Element is in last row ; Element is in first column ; Recursion for sub - matrix . & A [ 1 ] [ 1 ] is address to next inside sub matrix . ; Driver code | MAX = 100 NEW_LINE def findK ( A , n , m , k ) : NEW_LINE INDENT if ( n < 1 or m < 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( k <= m ) : NEW_LINE INDENT return A [ 0 ] [ k - 1 ] NEW_LINE DEDENT if ( k <= ( m + n - 1 ) ) : NEW_LINE INDENT return A [ ( k - m ) ] [ m - 1 ] NEW_LINE DEDENT if ( k <= ( m + n - 1 + m - 1 ) ) : NEW_LINE INDENT return A [ n - 1 ] [ m - 1 - ( k - ( m + n - 1 ) ) ] NEW_LINE DEDENT if ( k <= ( m + n - 1 + m - 1 + n - 2 ) ) : NEW_LINE INDENT return A [ n - 1 - ( k - ( m + n - 1 + m - 1 ) ) ] [ 0 ] NEW_LINE DEDENT A . pop ( 0 ) NEW_LINE [ j . pop ( 0 ) for j in A ] NEW_LINE return findK ( A , n - 2 , m - 2 , k - ( 2 * n + 2 * m - 4 ) ) NEW_LINE DEDENT a = [ [ 1 , 2 , 3 , 4 , 5 , 6 ] , [ 7 , 8 , 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 , 17 , 18 ] ] NEW_LINE k = 17 NEW_LINE print ( findK ( a , 3 , 6 , k ) ) NEW_LINE |
Find if given matrix is Toeplitz or not | Python3 program to check whether given matrix is a Toeplitz matrix or not ; Function to check if all elements present in descending diagonal starting from position ( i , j ) in the matrix are all same or not ; mismatch found ; we only reach here when all elements in given diagonal are same ; Function to check whether given matrix is a Toeplitz matrix or not ; do for each element in first row ; check descending diagonal starting from position ( 0 , j ) in the matrix ; do for each element in first column ; check descending diagonal starting from position ( i , 0 ) in the matrix ; we only reach here when each descending diagonal from left to right is same ; Driver Code ; Function call | N = 5 NEW_LINE M = 4 NEW_LINE def checkDiagonal ( mat , i , j ) : NEW_LINE INDENT res = mat [ i ] [ j ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE while ( i < N and j < M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != res ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def isToeplitz ( mat ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if not ( checkDiagonal ( mat , 0 , j ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if not ( checkDiagonal ( mat , i , 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 6 , 7 , 8 , 9 ] , [ 4 , 6 , 7 , 8 ] , [ 1 , 4 , 6 , 7 ] , [ 0 , 1 , 4 , 6 ] , [ 2 , 0 , 1 , 4 ] ] NEW_LINE if ( isToeplitz ( mat ) ) : NEW_LINE INDENT print ( " Matrix β is β a β Toeplitz " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Matrix β is β not β a β Toeplitz " ) NEW_LINE DEDENT DEDENT |
Find if given matrix is Toeplitz or not | Python3 program to check whether given matrix is a Toeplitz matrix or not ; row = number of rows col = number of columns ; dictionary to store key , value pairs ; if key value exists in the map , ; we check whether the current value stored in this key matches to element at current index or not . If not , return false ; else we put key , value pair in map ; Driver Code ; Function call | def isToeplitz ( matrix ) : NEW_LINE INDENT row = len ( matrix ) NEW_LINE col = len ( matrix [ 0 ] ) NEW_LINE map = { } NEW_LINE for i in range ( row ) : NEW_LINE INDENT for j in range ( col ) : NEW_LINE INDENT key = i - j NEW_LINE if ( key in map ) : NEW_LINE INDENT if ( map [ key ] != matrix [ i ] [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT map [ key ] = matrix [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT matrix = [ [ 12 , 23 , - 32 ] , [ - 20 , 12 , 23 ] , [ 56 , - 20 , 12 ] , [ 38 , 56 , - 20 ] ] NEW_LINE if ( isToeplitz ( matrix ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count zeros in a row wise and column wise sorted matrix | Python program to count number of 0 s in the given row - wise and column - wise sorted binary matrix . ; Function to count number of 0 s in the given row - wise and column - wise sorted binary matrix . ; start from bottom - left corner of the matrix ; stores number of zeroes in the matrix ; move up until you find a 0 ; if zero is not found in current column , we are done ; add 0 s present in current column to result ; move right to next column ; Driver Code | N = 5 ; NEW_LINE def countZeroes ( mat ) : NEW_LINE INDENT row = N - 1 ; NEW_LINE col = 0 ; NEW_LINE count = 0 ; NEW_LINE while ( col < N ) : NEW_LINE INDENT while ( mat [ row ] [ col ] ) : NEW_LINE INDENT if ( row < 0 ) : NEW_LINE INDENT return count ; NEW_LINE DEDENT row = row - 1 ; NEW_LINE DEDENT count = count + ( row + 1 ) ; NEW_LINE col = col + 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT mat = [ [ 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 1 , 1 ] , [ 0 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 ] ] ; NEW_LINE print ( countZeroes ( mat ) ) ; NEW_LINE |
Linked complete binary tree & its creation | For Queue Size ; A tree node ; A queue node ; A utility function to create a new tree node ; A utility function to create a new Queue ; Standard Queue Functions ; A utility function to check if a tree node has both left and right children ; Function to insert a new node in complete binary tree ; Create a new node for given data ; If the tree is empty , initialize the root with new node . ; get the front node of the queue . ; If the left child of this front node doesn t exist , set the left child as the new node ; If the right child of this front node doesn t exist , set the right child as the new node ; If the front node has both the left child and right child , Dequeue ( ) it . ; Enqueue ( ) the new node for later insertions ; Standard level order traversal to test above function ; Driver code | SIZE = 50 NEW_LINE class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . right = None NEW_LINE self . left = None NEW_LINE DEDENT DEDENT class Queue : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . front = None NEW_LINE self . rear = None NEW_LINE self . size = 0 NEW_LINE self . array = [ ] NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = node ( data ) NEW_LINE return temp NEW_LINE DEDENT def createQueue ( size ) : NEW_LINE INDENT global queue NEW_LINE queue = Queue ( ) ; NEW_LINE queue . front = queue . rear = - 1 ; NEW_LINE queue . size = size ; NEW_LINE queue . array = [ None for i in range ( size ) ] NEW_LINE return queue ; NEW_LINE DEDENT def isEmpty ( queue ) : NEW_LINE INDENT return queue . front == - 1 NEW_LINE DEDENT def isFull ( queue ) : NEW_LINE INDENT return queue . rear == queue . size - 1 ; NEW_LINE DEDENT def hasOnlyOneItem ( queue ) : NEW_LINE INDENT return queue . front == queue . rear ; NEW_LINE DEDENT def Enqueue ( root ) : NEW_LINE INDENT if ( isFull ( queue ) ) : NEW_LINE INDENT return ; NEW_LINE DEDENT queue . rear += 1 NEW_LINE queue . array [ queue . rear ] = root ; NEW_LINE if ( isEmpty ( queue ) ) : NEW_LINE INDENT queue . front += 1 ; NEW_LINE DEDENT DEDENT def Dequeue ( ) : NEW_LINE INDENT if ( isEmpty ( queue ) ) : NEW_LINE INDENT return None ; NEW_LINE DEDENT temp = queue . array [ queue . front ] ; NEW_LINE if ( hasOnlyOneItem ( queue ) ) : NEW_LINE INDENT queue . front = queue . rear = - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT queue . front += 1 NEW_LINE DEDENT return temp ; NEW_LINE DEDENT def getFront ( queue ) : NEW_LINE INDENT return queue . array [ queue . front ] ; NEW_LINE DEDENT def hasBothChild ( temp ) : NEW_LINE INDENT return ( temp and temp . left and temp . right ) ; NEW_LINE DEDENT def insert ( root , data , queue ) : NEW_LINE INDENT temp = newNode ( data ) ; NEW_LINE if not root : NEW_LINE INDENT root = temp ; NEW_LINE DEDENT else : NEW_LINE INDENT front = getFront ( queue ) ; NEW_LINE if ( not front . left ) : NEW_LINE INDENT front . left = temp ; NEW_LINE DEDENT elif ( not front . right ) : NEW_LINE INDENT front . right = temp ; NEW_LINE DEDENT if ( hasBothChild ( front ) ) : NEW_LINE INDENT Dequeue ( ) ; NEW_LINE DEDENT DEDENT Enqueue ( temp ) ; NEW_LINE return root NEW_LINE DEDENT def levelOrder ( root ) : NEW_LINE INDENT queue = createQueue ( SIZE ) ; NEW_LINE Enqueue ( root ) ; NEW_LINE while ( not isEmpty ( queue ) ) : NEW_LINE INDENT temp = Dequeue ( ) ; NEW_LINE print ( temp . data , end = ' β ' ) NEW_LINE if ( temp . left ) : NEW_LINE INDENT Enqueue ( temp . left ) ; NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT Enqueue ( temp . right ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = None NEW_LINE queue = createQueue ( SIZE ) ; NEW_LINE for i in range ( 1 , 13 ) : NEW_LINE INDENT root = insert ( root , i , queue ) ; NEW_LINE DEDENT levelOrder ( root ) ; NEW_LINE DEDENT |
Find size of the largest ' + ' formed by all ones in a binary matrix | size of binary square matrix ; Function to find the size of the largest ' + ' formed by all 1 's in given binary matrix ; left [ j ] [ j ] , right [ i ] [ j ] , top [ i ] [ j ] and bottom [ i ] [ j ] store maximum number of consecutive 1 's present to the left, right, top and bottom of mat[i][j] including cell(i, j) respectively ; initialize above four matrix ; initialize first row of top ; initialize last row of bottom ; initialize first column of left ; initialize last column of right ; fill all cells of above four matrix ; calculate left matrix ( filled left to right ) ; calculate top matrix ; calculate new value of j to calculate value of bottom ( i , j ) and right ( i , j ) ; calculate bottom matrix ; calculate right matrix ; revert back to old j ; n stores length of longest ' + ' found so far ; compute longest + ; find minimum of left ( i , j ) , right ( i , j ) , top ( i , j ) , bottom ( i , j ) ; largest + would be formed by a cell that has maximum value ; 4 directions of length n - 1 and 1 for middle cell ; matrix contains all 0 's ; Driver Code | N = 10 NEW_LINE def findLargestPlus ( mat ) : NEW_LINE INDENT left = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE right = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE top = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE bottom = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT top [ 0 ] [ i ] = mat [ 0 ] [ i ] NEW_LINE bottom [ N - 1 ] [ i ] = mat [ N - 1 ] [ i ] NEW_LINE left [ i ] [ 0 ] = mat [ i ] [ 0 ] NEW_LINE right [ i ] [ N - 1 ] = mat [ i ] [ N - 1 ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( 1 , N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT left [ i ] [ j ] = left [ i ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT left [ i ] [ j ] = 0 NEW_LINE DEDENT if ( mat [ j ] [ i ] == 1 ) : NEW_LINE INDENT top [ j ] [ i ] = top [ j - 1 ] [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT top [ j ] [ i ] = 0 NEW_LINE DEDENT j = N - 1 - j NEW_LINE if ( mat [ j ] [ i ] == 1 ) : NEW_LINE INDENT bottom [ j ] [ i ] = bottom [ j + 1 ] [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT bottom [ j ] [ i ] = 0 NEW_LINE DEDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT right [ i ] [ j ] = right [ i ] [ j + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right [ i ] [ j ] = 0 NEW_LINE DEDENT j = N - 1 - j NEW_LINE DEDENT DEDENT n = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT l = min ( min ( top [ i ] [ j ] , bottom [ i ] [ j ] ) , min ( left [ i ] [ j ] , right [ i ] [ j ] ) ) NEW_LINE if ( l > n ) : NEW_LINE INDENT n = l NEW_LINE DEDENT DEDENT DEDENT if ( n ) : NEW_LINE INDENT return 4 * ( n - 1 ) + 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 ] , [ 1 , 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 ] , [ 1 , 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 0 ] , [ 1 , 1 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 ] , [ 1 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 ] , [ 1 , 1 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 0 ] ] NEW_LINE print ( findLargestPlus ( mat ) ) NEW_LINE DEDENT |
Return previous element in an expanding matrix | Returns left of str in an expanding matrix of a , b , c , and d . ; Start from rightmost position ; If the current character is b or d , change to a or c respectively and break the loop ; If the current character is a or c , change it to b or d respectively ; Driver Code | def findLeft ( str ) : NEW_LINE INDENT n = len ( str ) - 1 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( str [ n ] == ' d ' ) : NEW_LINE INDENT str = str [ 0 : n ] + ' c ' + str [ n + 1 : ] ; NEW_LINE break ; NEW_LINE DEDENT if ( str [ n ] == ' b ' ) : NEW_LINE INDENT str = str [ 0 : n ] + ' a ' + str [ n + 1 : ] ; NEW_LINE break ; NEW_LINE DEDENT if ( str [ n ] == ' a ' ) : NEW_LINE INDENT str = str [ 0 : n ] + ' b ' + str [ n + 1 : ] ; NEW_LINE DEDENT elif ( str [ n ] == ' c ' ) : NEW_LINE INDENT str = str [ 0 : n ] + ' d ' + str [ n + 1 : ] ; NEW_LINE DEDENT n -= 1 ; NEW_LINE DEDENT return str ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aacbddc " ; NEW_LINE print ( " Left β of " , str , " is " , findLeft ( str ) ) ; NEW_LINE DEDENT |
Print n x n spiral matrix using O ( 1 ) extra space | Prints spiral matrix of size n x n containing numbers from 1 to n x n ; Finds minimum of four inputs ; For upper right half ; For lower left half ; Driver code ; print a n x n spiral matrix in O ( 1 ) space | def printSpiral ( n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT x = min ( min ( i , j ) , min ( n - 1 - i , n - 1 - j ) ) NEW_LINE if ( i <= j ) : NEW_LINE INDENT print ( ( n - 2 * x ) * ( n - 2 * x ) - ( i - x ) - ( j - x ) , end = " TABSYMBOL " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( ( n - 2 * x - 2 ) * ( n - 2 * x - 2 ) + ( i - x ) + ( j - x ) ) , end = " TABSYMBOL " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE printSpiral ( n ) NEW_LINE |
Shortest path in a Binary Maze | Python program to find the shortest path between a given source cell to a destination cell . ; To store matrix cell cordinates ; A data structure for queue used in BFS ; The cordinates of the cell ; Cell 's distance from the source ; Check whether given cell ( row , col ) is a valid cell or not ; return true if row number and column number is in range ; These arrays are used to get row and column numbers of 4 neighbours of a given cell ; Function to find the shortest path between a given source cell to a destination cell . ; check source and destination cell of the matrix have value 1 ; Mark the source cell as visited ; Create a queue for BFS ; Distance of source cell is 0 ; Enqueue source cell ; Do a BFS starting from source cell ; If we have reached the destination cell , we are done ; Otherwise enqueue its adjacent cells ; if adjacent cell is valid , has path and not visited yet , enqueue it . ; mark cell as visited and enqueue it ; Return - 1 if destination cannot be reached ; Driver code | from collections import deque NEW_LINE ROW = 9 NEW_LINE COL = 10 NEW_LINE class Point : NEW_LINE INDENT def __init__ ( self , x : int , y : int ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT class queueNode : NEW_LINE INDENT def __init__ ( self , pt : Point , dist : int ) : NEW_LINE INDENT self . pt = pt NEW_LINE self . dist = dist NEW_LINE DEDENT DEDENT def isValid ( row : int , col : int ) : NEW_LINE INDENT return ( row >= 0 ) and ( row < ROW ) and ( col >= 0 ) and ( col < COL ) NEW_LINE DEDENT rowNum = [ - 1 , 0 , 0 , 1 ] NEW_LINE colNum = [ 0 , - 1 , 1 , 0 ] NEW_LINE def BFS ( mat , src : Point , dest : Point ) : NEW_LINE INDENT if mat [ src . x ] [ src . y ] != 1 or mat [ dest . x ] [ dest . y ] != 1 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT visited = [ [ False for i in range ( COL ) ] for j in range ( ROW ) ] NEW_LINE visited [ src . x ] [ src . y ] = True NEW_LINE q = deque ( ) NEW_LINE s = queueNode ( src , 0 ) NEW_LINE q . append ( s ) NEW_LINE while q : NEW_LINE INDENT curr = q . popleft ( ) NEW_LINE pt = curr . pt NEW_LINE if pt . x == dest . x and pt . y == dest . y : NEW_LINE INDENT return curr . dist NEW_LINE DEDENT for i in range ( 4 ) : NEW_LINE INDENT row = pt . x + rowNum [ i ] NEW_LINE col = pt . y + colNum [ i ] NEW_LINE if ( isValid ( row , col ) and mat [ row ] [ col ] == 1 and not visited [ row ] [ col ] ) : NEW_LINE INDENT visited [ row ] [ col ] = True NEW_LINE Adjcell = queueNode ( Point ( row , col ) , curr . dist + 1 ) NEW_LINE q . append ( Adjcell ) NEW_LINE DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT mat = [ [ 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 ] , [ 1 , 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 ] , [ 1 , 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 1 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 0 ] , [ 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 ] , [ 1 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 1 ] ] NEW_LINE source = Point ( 0 , 0 ) NEW_LINE dest = Point ( 3 , 4 ) NEW_LINE dist = BFS ( mat , source , dest ) NEW_LINE if dist != - 1 : NEW_LINE INDENT print ( " Shortest β Path β is " , dist ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Shortest β Path β doesn ' t β exist " ) NEW_LINE DEDENT DEDENT main ( ) NEW_LINE |
Convert a given Binary Tree to Doubly Linked List | Set 1 | Binary tree Node class has data , left and right child ; This is a utility function to convert the binary tree to doubly linked list . Most of the core task is done by this function . ; Base case ; Convert left subtree and link to root ; Convert the left subtree ; Find inorder predecessor , After this loop , left will point to the inorder predecessor of root ; Make root as next of predecessor ; Make predecessor as previous of root ; Convert the right subtree and link to root ; Convert the right subtree ; Find inorder successor , After this loop , right will point to the inorder successor of root ; Make root as previous of successor ; Make successor as next of root ; The main function that first calls bintree2listUtil ( ) , then follows step 3 of the above algorithm ; Base case ; Convert to doubly linked list using BLLToDLLUtil ; We need pointer to left most node which is head of the constructed Doubly Linked list ; Function to print the given doubly linked list ; Driver Code ; Let us create the tree shown in above diagram ; Convert to DLL ; Print the converted list | class Node ( object ) : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def BTToDLLUtil ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return root NEW_LINE DEDENT if root . left : NEW_LINE INDENT left = BTToDLLUtil ( root . left ) NEW_LINE while left . right : NEW_LINE INDENT left = left . right NEW_LINE DEDENT left . right = root NEW_LINE root . left = left NEW_LINE DEDENT if root . right : NEW_LINE INDENT right = BTToDLLUtil ( root . right ) NEW_LINE while right . left : NEW_LINE INDENT right = right . left NEW_LINE DEDENT right . left = root NEW_LINE root . right = right NEW_LINE DEDENT return root NEW_LINE DEDENT def BTToDLL ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return root NEW_LINE DEDENT root = BTToDLLUtil ( root ) NEW_LINE while root . left : NEW_LINE INDENT root = root . left NEW_LINE DEDENT return root NEW_LINE DEDENT def print_list ( head ) : NEW_LINE INDENT if head is None : NEW_LINE INDENT return NEW_LINE DEDENT while head : NEW_LINE INDENT print ( head . data , end = " β " ) NEW_LINE head = head . right NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 12 ) NEW_LINE root . right = Node ( 15 ) NEW_LINE root . left . left = Node ( 25 ) NEW_LINE root . left . right = Node ( 30 ) NEW_LINE root . right . left = Node ( 36 ) NEW_LINE head = BTToDLL ( root ) NEW_LINE print_list ( head ) NEW_LINE DEDENT |
A Boolean Matrix Question | Python3 Code For A Boolean Matrix Question ; Initialize all values of row [ ] as 0 ; Initialize all values of col [ ] as 0 ; Store the rows and columns to be marked as 1 in row [ ] and col [ ] arrays respectively ; Modify the input matrix mat [ ] using the above constructed row [ ] and col [ ] arrays ; A utility function to print a 2D matrix ; Driver Code | R = 3 NEW_LINE C = 4 NEW_LINE def modifyMatrix ( mat ) : NEW_LINE INDENT row = [ 0 ] * R NEW_LINE col = [ 0 ] * C NEW_LINE for i in range ( 0 , R ) : NEW_LINE INDENT row [ i ] = 0 NEW_LINE DEDENT for i in range ( 0 , C ) : NEW_LINE INDENT col [ i ] = 0 NEW_LINE DEDENT for i in range ( 0 , R ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT row [ i ] = 1 NEW_LINE col [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 0 , R ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_LINE INDENT if ( row [ i ] == 1 or col [ j ] == 1 ) : NEW_LINE INDENT mat [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def printMatrix ( mat ) : NEW_LINE INDENT for i in range ( 0 , R ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 0 , 0 , 1 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 ] ] NEW_LINE print ( " Input β Matrix β n " ) NEW_LINE printMatrix ( mat ) NEW_LINE modifyMatrix ( mat ) NEW_LINE print ( " Matrix β after β modification β n " ) NEW_LINE printMatrix ( mat ) NEW_LINE |
A Boolean Matrix Question | Python3 Code For A Boolean Matrix Question ; variables to check if there are any 1 in first row and column ; updating the first row and col if 1 is encountered ; Modify the input matrix mat [ ] using the first row and first column of Matrix mat ; modify first row if there was any 1 ; modify first col if there was any 1 ; A utility function to print a 2D matrix ; Driver Code | def modifyMatrix ( mat ) : NEW_LINE INDENT row_flag = False NEW_LINE col_flag = False NEW_LINE for i in range ( 0 , len ( mat ) ) : NEW_LINE INDENT for j in range ( 0 , len ( mat ) ) : NEW_LINE INDENT if ( i == 0 and mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT row_flag = True NEW_LINE DEDENT if ( j == 0 and mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT col_flag = True NEW_LINE DEDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT mat [ 0 ] [ j ] = 1 NEW_LINE mat [ i ] [ 0 ] = 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , len ( mat ) ) : NEW_LINE INDENT for j in range ( 1 , len ( mat ) + 1 ) : NEW_LINE INDENT if ( mat [ 0 ] [ j ] == 1 or mat [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT mat [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT if ( row_flag == True ) : NEW_LINE INDENT for i in range ( 0 , len ( mat ) ) : NEW_LINE INDENT mat [ 0 ] [ i ] = 1 NEW_LINE DEDENT DEDENT if ( col_flag == True ) : NEW_LINE INDENT for i in range ( 0 , len ( mat ) ) : NEW_LINE INDENT mat [ i ] [ 0 ] = 1 NEW_LINE DEDENT DEDENT DEDENT def printMatrix ( mat ) : NEW_LINE INDENT for i in range ( 0 , len ( mat ) ) : NEW_LINE INDENT for j in range ( 0 , len ( mat ) + 1 ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 0 , 0 , 1 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 ] ] NEW_LINE print ( " Input β Matrix β : " ) NEW_LINE printMatrix ( mat ) NEW_LINE modifyMatrix ( mat ) NEW_LINE print ( " Matrix β After β Modification β : " ) NEW_LINE printMatrix ( mat ) NEW_LINE |
Given a Boolean Matrix , find k such that all elements in k ' th β row β are β 0 β and β k ' th column are 1. | Python program to find k such that all elements in k ' th β row β β β are β 0 β and β k ' th column are 1 ; start from top right - most corner ; initialise result ; find the index ( This loop runs at most 2 n times , we either increment row number or decrement column number ) ; if the current element is 0 , then this row may be a solution ; check for all the elements in this row ; if all values are 0 , update result as row number ; if found a 1 in current row , the row can 't be a solution, increment row number ; if the current element is 1 ; check for all the elements in this column ; if all elements are 1 , update result as col number ; if found a 0 in current column , the column can 't be a solution, decrement column number ; if we couldn ' t β find β result β in β above β loop , β result β doesn ' t exist ; check if the above computed res value is valid ; test find ( arr ) function | def find ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE res = - 1 NEW_LINE while i < n and j >= 0 : NEW_LINE INDENT if arr [ i ] [ j ] == 0 : NEW_LINE INDENT while j >= 0 and ( arr [ i ] [ j ] == 0 or i == j ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if j == - 1 : NEW_LINE INDENT res = i NEW_LINE break NEW_LINE DEDENT else : i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT while i < n and ( arr [ i ] [ j ] == 1 or i == j ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if i == n : NEW_LINE INDENT res = j NEW_LINE break NEW_LINE DEDENT else : j -= 1 NEW_LINE DEDENT DEDENT if res == - 1 : NEW_LINE INDENT return res NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if res != i and arr [ i ] [ res ] != 1 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT for j in range ( 0 , j ) : NEW_LINE INDENT if res != j and arr [ res ] [ j ] != 0 : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT arr = [ [ 0 , 0 , 1 , 1 , 0 ] , [ 0 , 0 , 0 , 1 , 0 ] , [ 1 , 1 , 1 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 ] , [ 1 , 1 , 1 , 1 , 1 ] ] NEW_LINE print find ( arr ) NEW_LINE |
Print unique rows in a given boolean matrix | Given a binary matrix of M X N of integers , you need to return only unique rows of binary array ; The main function that prints all unique rows in a given matrix . ; Traverse through the matrix ; Check if there is similar column is already printed , i . e if i and jth column match . ; If no row is similar ; Print the row ; Driver Code | ROW = 4 NEW_LINE COL = 5 NEW_LINE def findUniqueRows ( M ) : NEW_LINE INDENT for i in range ( ROW ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT flag = 1 NEW_LINE for k in range ( COL ) : NEW_LINE INDENT if ( M [ i ] [ k ] != M [ j ] [ k ] ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT print ( M [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = [ [ 0 , 1 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 0 ] , [ 0 , 1 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 0 , 0 ] ] NEW_LINE findUniqueRows ( M ) NEW_LINE DEDENT |
Print unique rows in a given boolean matrix | Python3 code to print unique row in a given binary matrix ; Driver Code | def printArray ( matrix ) : NEW_LINE INDENT rowCount = len ( matrix ) NEW_LINE if rowCount == 0 : NEW_LINE INDENT return NEW_LINE DEDENT columnCount = len ( matrix [ 0 ] ) NEW_LINE if columnCount == 0 : NEW_LINE INDENT return NEW_LINE DEDENT row_output_format = " β " . join ( [ " % s " ] * columnCount ) NEW_LINE printed = { } NEW_LINE for row in matrix : NEW_LINE INDENT routput = row_output_format % tuple ( row ) NEW_LINE if routput not in printed : NEW_LINE INDENT printed [ routput ] = True NEW_LINE print ( routput ) NEW_LINE DEDENT DEDENT DEDENT mat = [ [ 0 , 1 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 0 ] , [ 0 , 1 , 0 , 0 , 1 ] , [ 1 , 1 , 1 , 0 , 0 ] ] NEW_LINE printArray ( mat ) NEW_LINE |
Find the largest rectangle of 1 's with swapping of columns allowed | Python 3 program to find the largest rectangle of 1 's with swapping of columns allowed. ; Returns area of the largest rectangle of 1 's ; An auxiliary array to store count of consecutive 1 's in every column. ; Step 1 : Fill the auxiliary array hist [ ] [ ] ; First row in hist [ ] [ ] is copy of first row in mat [ ] [ ] ; Fill remaining rows of hist [ ] [ ] ; Step 2 : Sort rows of hist [ ] [ ] in non - increasing order ; counting occurrence ; Traverse the count array from right side ; Step 3 : Traverse the sorted hist [ ] [ ] to find maximum area ; Since values are in decreasing order , The area ending with cell ( i , j ) can be obtained by multiplying column number with value of hist [ i ] [ j ] ; Driver Code | R = 3 NEW_LINE C = 5 NEW_LINE def maxArea ( mat ) : NEW_LINE INDENT hist = [ [ 0 for i in range ( C + 1 ) ] for i in range ( R + 1 ) ] NEW_LINE for i in range ( 0 , C , 1 ) : NEW_LINE INDENT hist [ 0 ] [ i ] = mat [ 0 ] [ i ] NEW_LINE for j in range ( 1 , R , 1 ) : NEW_LINE INDENT if ( ( mat [ j ] [ i ] == 0 ) ) : NEW_LINE INDENT hist [ j ] [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT hist [ j ] [ i ] = hist [ j - 1 ] [ i ] + 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 0 , R , 1 ) : NEW_LINE INDENT count = [ 0 for i in range ( R + 1 ) ] NEW_LINE for j in range ( 0 , C , 1 ) : NEW_LINE INDENT count [ hist [ i ] [ j ] ] += 1 NEW_LINE DEDENT col_no = 0 NEW_LINE j = R NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( count [ j ] > 0 ) : NEW_LINE INDENT for k in range ( 0 , count [ j ] , 1 ) : NEW_LINE INDENT hist [ i ] [ col_no ] = j NEW_LINE col_no += 1 NEW_LINE DEDENT DEDENT j -= 1 NEW_LINE DEDENT DEDENT max_area = 0 NEW_LINE for i in range ( 0 , R , 1 ) : NEW_LINE INDENT for j in range ( 0 , C , 1 ) : NEW_LINE INDENT curr_area = ( j + 1 ) * hist [ i ] [ j ] NEW_LINE if ( curr_area > max_area ) : NEW_LINE INDENT max_area = curr_area NEW_LINE DEDENT DEDENT DEDENT return max_area NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 0 , 1 , 0 , 1 , 0 ] , [ 0 , 1 , 0 , 1 , 1 ] , [ 1 , 1 , 0 , 1 , 0 ] ] NEW_LINE print ( " Area β of β the β largest β rectangle β is " , maxArea ( mat ) ) NEW_LINE DEDENT |
Submatrix Sum Queries | Python 3 program to compute submatrix query sum in O ( 1 ) time ; Function to preprcess input mat [ M ] [ N ] . This function mainly fills aux [ M ] [ N ] such that aux [ i ] [ j ] stores sum of elements from ( 0 , 0 ) to ( i , j ) ; Copy first row of mat [ ] [ ] to aux [ ] [ ] ; Do column wise sum ; Do row wise sum ; A O ( 1 ) time function to compute sum of submatrix between ( tli , tlj ) and ( rbi , rbj ) using aux [ ] [ ] which is built by the preprocess function ; result is now sum of elements between ( 0 , 0 ) and ( rbi , rbj ) ; Remove elements between ( 0 , 0 ) and ( tli - 1 , rbj ) ; Remove elements between ( 0 , 0 ) and ( rbi , tlj - 1 ) ; Add aux [ tli - 1 ] [ tlj - 1 ] as elements between ( 0 , 0 ) and ( tli - 1 , tlj - 1 ) are subtracted twice ; Driver Code | M = 4 NEW_LINE N = 5 NEW_LINE def preProcess ( mat , aux ) : NEW_LINE INDENT for i in range ( 0 , N , 1 ) : NEW_LINE INDENT aux [ 0 ] [ i ] = mat [ 0 ] [ i ] NEW_LINE DEDENT for i in range ( 1 , M , 1 ) : NEW_LINE INDENT for j in range ( 0 , N , 1 ) : NEW_LINE INDENT aux [ i ] [ j ] = mat [ i ] [ j ] + aux [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( 0 , M , 1 ) : NEW_LINE INDENT for j in range ( 1 , N , 1 ) : NEW_LINE INDENT aux [ i ] [ j ] += aux [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT def sumQuery ( aux , tli , tlj , rbi , rbj ) : NEW_LINE INDENT res = aux [ rbi ] [ rbj ] NEW_LINE if ( tli > 0 ) : NEW_LINE INDENT res = res - aux [ tli - 1 ] [ rbj ] NEW_LINE DEDENT if ( tlj > 0 ) : NEW_LINE INDENT res = res - aux [ rbi ] [ tlj - 1 ] NEW_LINE DEDENT if ( tli > 0 and tlj > 0 ) : NEW_LINE INDENT res = res + aux [ tli - 1 ] [ tlj - 1 ] NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 , 4 , 6 ] , [ 5 , 3 , 8 , 1 , 2 ] , [ 4 , 6 , 7 , 5 , 5 ] , [ 2 , 4 , 8 , 9 , 4 ] ] NEW_LINE DEDENT aux = [ [ 0 for i in range ( N ) ] for j in range ( M ) ] NEW_LINE preProcess ( mat , aux ) NEW_LINE tli = 2 NEW_LINE tlj = 2 NEW_LINE rbi = 3 NEW_LINE rbj = 4 NEW_LINE print ( " Query1 : " , sumQuery ( aux , tli , tlj , rbi , rbj ) ) NEW_LINE tli = 0 NEW_LINE tlj = 0 NEW_LINE rbi = 1 NEW_LINE rbj = 1 NEW_LINE print ( " Query2 : " , sumQuery ( aux , tli , tlj , rbi , rbj ) ) NEW_LINE tli = 1 NEW_LINE tlj = 2 NEW_LINE rbi = 3 NEW_LINE rbj = 3 NEW_LINE print ( " Query3 : " , sumQuery ( aux , tli , tlj , rbi , rbj ) ) NEW_LINE |
Program for Rank of Matrix | Python 3 program to find rank of a matrix ; Function for exchanging two rows of a matrix ; Find rank of a matrix ; Before we visit current row ' row ' , we make sure that mat [ row ] [ 0 ] , ... . mat [ row ] [ row - 1 ] are 0. Diagonal element is not zero ; This makes all entries of current column as 0 except entry 'mat[row][row] ; Diagonal element is already zero . Two cases arise : 1 ) If there is a row below it with non - zero entry , then swap this row with that row and process that row 2 ) If all elements in current column below mat [ r ] [ row ] are 0 , then remvoe this column by swapping it with last column and reducing number of columns by 1. ; Find the non - zero element in current column ; Swap the row with non - zero element with this row . ; If we did not find any row with non - zero element in current columnm , then all values in this column are 0. ; Reduce number of columns ; copy the last column here ; process this row again ; self . Display ( Matrix , self . R , self . C ) ; Function to Display a matrix ; Driver Code | class rankMatrix ( object ) : NEW_LINE INDENT def __init__ ( self , Matrix ) : NEW_LINE INDENT self . R = len ( Matrix ) NEW_LINE self . C = len ( Matrix [ 0 ] ) NEW_LINE DEDENT def swap ( self , Matrix , row1 , row2 , col ) : NEW_LINE INDENT for i in range ( col ) : NEW_LINE INDENT temp = Matrix [ row1 ] [ i ] NEW_LINE Matrix [ row1 ] [ i ] = Matrix [ row2 ] [ i ] NEW_LINE Matrix [ row2 ] [ i ] = temp NEW_LINE DEDENT DEDENT def rankOfMatrix ( self , Matrix ) : NEW_LINE INDENT rank = self . C NEW_LINE for row in range ( 0 , rank , 1 ) : NEW_LINE INDENT if Matrix [ row ] [ row ] != 0 : NEW_LINE INDENT for col in range ( 0 , self . R , 1 ) : NEW_LINE INDENT if col != row : NEW_LINE INDENT multiplier = ( Matrix [ col ] [ row ] / Matrix [ row ] [ row ] ) NEW_LINE for i in range ( rank ) : NEW_LINE INDENT Matrix [ col ] [ i ] -= ( multiplier * Matrix [ row ] [ i ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT else : NEW_LINE INDENT reduce = True NEW_LINE for i in range ( row + 1 , self . R , 1 ) : NEW_LINE INDENT if Matrix [ i ] [ row ] != 0 : NEW_LINE INDENT self . swap ( Matrix , row , i , rank ) NEW_LINE reduce = False NEW_LINE break NEW_LINE DEDENT DEDENT if reduce : NEW_LINE INDENT rank -= 1 NEW_LINE for i in range ( 0 , self . R , 1 ) : NEW_LINE INDENT Matrix [ i ] [ row ] = Matrix [ i ] [ rank ] NEW_LINE DEDENT DEDENT row -= 1 NEW_LINE DEDENT DEDENT return ( rank ) NEW_LINE DEDENT def Display ( self , Matrix , row , col ) : NEW_LINE INDENT for i in range ( row ) : NEW_LINE INDENT for j in range ( col ) : NEW_LINE INDENT print ( " β " + str ( Matrix [ i ] [ j ] ) ) NEW_LINE DEDENT print ( ' ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Matrix = [ [ 10 , 20 , 10 ] , [ - 20 , - 30 , 10 ] , [ 30 , 50 , 0 ] ] NEW_LINE RankMatrix = rankMatrix ( Matrix ) NEW_LINE print ( " Rank β of β the β Matrix β is : " , ( RankMatrix . rankOfMatrix ( Matrix ) ) ) NEW_LINE DEDENT |
Maximum size rectangle binary sub | Finds the maximum area under the histogram represented by histogram . See below article for details . ; Create an empty stack . The stack holds indexes of hist array / The bars stored in stack are always in increasing order of their heights . ; Top of stack ; Initialize max area in current ; row ( or histogram ) Initialize area with current top ; Run through all bars of given histogram ( or row ) ; If this bar is higher than the bar on top stack , push it to stack ; If this bar is lower than top of stack , then calculate area of rectangle with stack top as the smallest ( or minimum height ) bar . ' i ' is ' right β index ' for the top and element before top in stack is 'left index ; Now pop the remaining bars from stack and calculate area with every popped bar as the smallest bar ; Returns area of the largest rectangle with all 1 s in A ; Calculate area for first row and initialize it as result ; iterate over row to find maximum rectangular area considering each row as histogram ; if A [ i ] [ j ] is 1 then add A [ i - 1 ] [ j ] ; Update result if area with current row ( as last row ) of rectangle ) is more ; Driver Code | class Solution ( ) : NEW_LINE INDENT def maxHist ( self , row ) : NEW_LINE INDENT result = [ ] NEW_LINE top_val = 0 NEW_LINE max_area = 0 NEW_LINE area = 0 NEW_LINE i = 0 NEW_LINE while ( i < len ( row ) ) : NEW_LINE INDENT if ( len ( result ) == 0 ) or ( row [ result [ - 1 ] ] <= row [ i ] ) : NEW_LINE INDENT result . append ( i ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT top_val = row [ result . pop ( ) ] NEW_LINE area = top_val * i NEW_LINE if ( len ( result ) ) : NEW_LINE INDENT area = top_val * ( i - result [ - 1 ] - 1 ) NEW_LINE DEDENT max_area = max ( area , max_area ) NEW_LINE DEDENT DEDENT while ( len ( result ) ) : NEW_LINE INDENT top_val = row [ result . pop ( ) ] NEW_LINE area = top_val * i NEW_LINE if ( len ( result ) ) : NEW_LINE INDENT area = top_val * ( i - result [ - 1 ] - 1 ) NEW_LINE DEDENT max_area = max ( area , max_area ) NEW_LINE DEDENT return max_area NEW_LINE DEDENT def maxRectangle ( self , A ) : NEW_LINE INDENT result = self . maxHist ( A [ 0 ] ) NEW_LINE for i in range ( 1 , len ( A ) ) : NEW_LINE INDENT for j in range ( len ( A [ i ] ) ) : NEW_LINE INDENT if ( A [ i ] [ j ] ) : NEW_LINE INDENT A [ i ] [ j ] += A [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT result = max ( result , self . maxHist ( A [ i ] ) ) NEW_LINE DEDENT return result NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 0 , 1 , 1 , 0 ] , [ 1 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 ] , [ 1 , 1 , 0 , 0 ] ] NEW_LINE ans = Solution ( ) NEW_LINE print ( " Area β of β maximum β rectangle β is " , ans . maxRectangle ( A ) ) NEW_LINE DEDENT |
Find sum of all elements in a matrix except the elements in row and / or column of given cell ? | A structure to represent a cell index ; r is row , varies from 0 to R - 1 ; c is column , varies from 0 to C - 1 ; A simple solution to find sums for a given array of cell indexes ; Iterate through all cell indexes ; Compute sum for current cell index ; Driver Code | class Cell : NEW_LINE INDENT def __init__ ( self , r , c ) : NEW_LINE INDENT self . r = r NEW_LINE self . c = c NEW_LINE DEDENT DEDENT def printSums ( mat , arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT Sum = 0 ; r = arr [ i ] . r ; c = arr [ i ] . c NEW_LINE for j in range ( 0 , R ) : NEW_LINE INDENT for k in range ( 0 , C ) : NEW_LINE INDENT if j != r and k != c : NEW_LINE INDENT Sum += mat [ j ] [ k ] NEW_LINE DEDENT DEDENT DEDENT print ( Sum ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 1 , 2 ] , [ 3 , 4 , 6 ] , [ 5 , 3 , 2 ] ] NEW_LINE R = C = 3 NEW_LINE arr = [ Cell ( 0 , 0 ) , Cell ( 1 , 1 ) , Cell ( 0 , 1 ) ] NEW_LINE n = len ( arr ) NEW_LINE printSums ( mat , arr , n ) NEW_LINE DEDENT |
Find sum of all elements in a matrix except the elements in row and / or column of given cell ? | Python3 implementation of the approach A structure to represent a cell index ; r is row , varies from 0 to R - 1 ; c is column , varies from 0 to C - 1 ; Compute sum of all elements , sum of every row and sum every column ; Compute the desired sum for all given cell indexes ; Driver Code | class Cell : NEW_LINE INDENT def __init__ ( self , r , c ) : NEW_LINE INDENT self . r = r NEW_LINE self . c = c NEW_LINE DEDENT DEDENT def printSums ( mat , arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE row , col = [ 0 ] * R , [ 0 ] * C NEW_LINE for i in range ( 0 , R ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_LINE INDENT Sum += mat [ i ] [ j ] NEW_LINE row [ i ] += mat [ i ] [ j ] NEW_LINE col [ j ] += mat [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT r0 , c0 = arr [ i ] . r , arr [ i ] . c NEW_LINE print ( Sum - row [ r0 ] - col [ c0 ] + mat [ r0 ] [ c0 ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 1 , 2 ] , [ 3 , 4 , 6 ] , [ 5 , 3 , 2 ] ] NEW_LINE R = C = 3 NEW_LINE arr = [ Cell ( 0 , 0 ) , Cell ( 1 , 1 ) , Cell ( 0 , 1 ) ] NEW_LINE n = len ( arr ) NEW_LINE printSums ( mat , arr , n ) NEW_LINE DEDENT |
Count number of islands where every island is row | This function takes a matrix of ' X ' and ' O ' and returns the number of rectangular islands of ' X ' where no two islands are row - wise or column - wise adjacent , the islands may be diagonaly adjacent ; Initialize result ; Traverse the input matrix ; If current cell is ' X ' , then check whether this is top - leftmost of a rectangle . If yes , then increment count ; Driver Code | def countIslands ( mat ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == ' X ' ) : NEW_LINE INDENT if ( ( i == 0 or mat [ i - 1 ] [ j ] == ' O ' ) and ( j == 0 or mat [ i ] [ j - 1 ] == ' O ' ) ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT M = 6 NEW_LINE N = 3 NEW_LINE mat = [ [ ' O ' , ' O ' , ' O ' ] , [ ' X ' , ' X ' , ' O ' ] , [ ' X ' , ' X ' , ' O ' ] , [ ' O ' , ' O ' , ' X ' ] , [ ' O ' , ' O ' , ' X ' ] , [ ' X ' , ' X ' , ' O ' ] ] NEW_LINE print ( " Number β of β rectangular β islands β is " , countIslands ( mat ) ) NEW_LINE |
Find a common element in all rows of a given row | Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; An array to store indexes of current last column ; Initialize min_row as first row ; Keep finding min_row in current last column , till either all elements of last column become same or we hit first column . ; Find minimum in current last column ; eq_count is count of elements equal to minimum in current last column . ; Traverse current last column elements again to update it ; Decrease last column index of a row whose value is more than minimum . ; Reduce last column index by 1 ; If equal count becomes M , return the value ; Driver Code | M = 4 NEW_LINE N = 5 NEW_LINE def findCommon ( mat ) : NEW_LINE INDENT column = [ N - 1 ] * M NEW_LINE min_row = 0 NEW_LINE while ( column [ min_row ] >= 0 ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ column [ i ] ] < mat [ min_row ] [ column [ min_row ] ] ) : NEW_LINE INDENT min_row = i NEW_LINE DEDENT DEDENT eq_count = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ column [ i ] ] > mat [ min_row ] [ column [ min_row ] ] ) : NEW_LINE INDENT if ( column [ i ] == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT column [ i ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT eq_count += 1 NEW_LINE DEDENT DEDENT if ( eq_count == M ) : NEW_LINE INDENT return mat [ min_row ] [ column [ min_row ] ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 2 , 4 , 5 , 8 , 10 ] , [ 3 , 5 , 7 , 9 , 11 ] , [ 1 , 3 , 5 , 7 , 9 ] ] NEW_LINE result = findCommon ( mat ) NEW_LINE if ( result == - 1 ) : NEW_LINE INDENT print ( " No β common β element " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Common β element β is " , result ) NEW_LINE DEDENT DEDENT |
Find a common element in all rows of a given row | Python3 implementation of the approach ; Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; A hash map to store count of elements ; Increment the count of first element of the row ; Starting from the second element of the current row ; If current element is different from the previous element i . e . it is appearing for the first time in the current row ; Find element having count equal to number of rows ; No such element found ; Driver Code | from collections import defaultdict NEW_LINE M = 4 NEW_LINE N = 5 NEW_LINE def findCommon ( mat ) : NEW_LINE INDENT global M NEW_LINE global N NEW_LINE cnt = dict ( ) NEW_LINE cnt = defaultdict ( lambda : 0 , cnt ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i < M ) : NEW_LINE INDENT cnt [ mat [ i ] [ 0 ] ] = cnt [ mat [ i ] [ 0 ] ] + 1 NEW_LINE j = 1 NEW_LINE while ( j < N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != mat [ i ] [ j - 1 ] ) : NEW_LINE INDENT cnt [ mat [ i ] [ j ] ] = cnt [ mat [ i ] [ j ] ] + 1 NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT for ele in cnt : NEW_LINE INDENT if ( cnt [ ele ] == M ) : NEW_LINE INDENT return ele NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT mat = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 2 , 4 , 5 , 8 , 10 ] , [ 3 , 5 , 7 , 9 , 11 ] , [ 1 , 3 , 5 , 7 , 9 ] , ] NEW_LINE result = findCommon ( mat ) NEW_LINE if ( result == - 1 ) : NEW_LINE INDENT print ( " No β common β element " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Common β element β is β " , result ) NEW_LINE DEDENT |
Given a matrix of β O β and β X β , replace ' O ' with ' X ' if surrounded by ' X ' | Size of given matrix is M x N ; A recursive function to replace previous value ' prevV ' at ' ( x , β y ) ' and all surrounding values of ( x , y ) with new value ' newV ' . ; Base Cases ; Replace the color at ( x , y ) ; Recur for north , east , south and west ; Returns size of maximum size subsquare matrix surrounded by 'X ; Step 1 : Replace all ' O ' s with '- ; Call floodFill for all ' - ' lying on edges Left Side ; Right side ; Top side ; Bottom side ; Step 3 : Replace all ' - ' with 'X ; Driver code | M = 6 NEW_LINE N = 6 NEW_LINE def floodFillUtil ( mat , x , y , prevV , newV ) : NEW_LINE INDENT if ( x < 0 or x >= M or y < 0 or y >= N ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( mat [ x ] [ y ] != prevV ) : NEW_LINE INDENT return NEW_LINE DEDENT mat [ x ] [ y ] = newV NEW_LINE floodFillUtil ( mat , x + 1 , y , prevV , newV ) NEW_LINE floodFillUtil ( mat , x - 1 , y , prevV , newV ) NEW_LINE floodFillUtil ( mat , x , y + 1 , prevV , newV ) NEW_LINE floodFillUtil ( mat , x , y - 1 , prevV , newV ) NEW_LINE DEDENT def replaceSurrounded ( mat ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == ' O ' ) : NEW_LINE INDENT mat [ i ] [ j ] = ' - ' NEW_LINE DEDENT DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ 0 ] == ' - ' ) : NEW_LINE INDENT floodFillUtil ( mat , i , 0 , ' - ' , ' O ' ) NEW_LINE DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ N - 1 ] == ' - ' ) : NEW_LINE INDENT floodFillUtil ( mat , i , N - 1 , ' - ' , ' O ' ) NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( mat [ 0 ] [ i ] == ' - ' ) : NEW_LINE INDENT floodFillUtil ( mat , 0 , i , ' - ' , ' O ' ) NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( mat [ M - 1 ] [ i ] == ' - ' ) : NEW_LINE INDENT floodFillUtil ( mat , M - 1 , i , ' - ' , ' O ' ) NEW_LINE DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == ' - ' ) : NEW_LINE INDENT mat [ i ] [ j ] = ' X ' NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ ' X ' , ' O ' , ' X ' , ' O ' , ' X ' , ' X ' ] , [ ' X ' , ' O ' , ' X ' , ' X ' , ' O ' , ' X ' ] , [ ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' X ' ] , [ ' O ' , ' X ' , ' X ' , ' X ' , ' X ' , ' X ' ] , [ ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' O ' ] , [ ' O ' , ' O ' , ' X ' , ' O ' , ' O ' , ' O ' ] ] ; NEW_LINE replaceSurrounded ( mat ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT print ( * mat [ i ] ) NEW_LINE DEDENT DEDENT |
Convert a given Binary Tree to Doubly Linked List | Set 2 | A Binary Tree node ; Standard Inorder traversal of tree ; Changes left pointers to work as previous pointers in converted DLL The function simply does inorder traversal of Binary Tree and updates left pointer using previously visited node ; Changes right pointers to work as nexr pointers in converted DLL ; Find the right most node in BT or last node in DLL ; Start from the rightmost node , traverse back using left pointers While traversing , change right pointer of nodes ; The leftmost node is head of linked list , return it ; The main function that converts BST to DLL and returns head of DLL ; Set the previous pointer ; Set the next pointer and return head of DLL ; Traversses the DLL from left to right ; Let us create the tree shown in above diagram | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print " TABSYMBOL % d " % ( root . data ) , NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT def fixPrevPtr ( root ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT fixPrevPtr ( root . left ) NEW_LINE root . left = fixPrevPtr . pre NEW_LINE fixPrevPtr . pre = root NEW_LINE fixPrevPtr ( root . right ) NEW_LINE DEDENT DEDENT def fixNextPtr ( root ) : NEW_LINE INDENT prev = None NEW_LINE while ( root and root . right != None ) : NEW_LINE INDENT root = root . right NEW_LINE DEDENT while ( root and root . left != None ) : NEW_LINE INDENT prev = root NEW_LINE root = root . left NEW_LINE root . right = prev NEW_LINE DEDENT return root NEW_LINE DEDENT def BTToDLL ( root ) : NEW_LINE INDENT fixPrevPtr ( root ) NEW_LINE return fixNextPtr ( root ) NEW_LINE DEDENT def printList ( root ) : NEW_LINE INDENT while ( root != None ) : NEW_LINE INDENT print " TABSYMBOL % d " % ( root . data ) , NEW_LINE root = root . right NEW_LINE DEDENT DEDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 12 ) NEW_LINE root . right = Node ( 15 ) NEW_LINE root . left . left = Node ( 25 ) NEW_LINE root . left . right = Node ( 30 ) NEW_LINE root . right . left = Node ( 36 ) NEW_LINE print " NEW_LINE INDENT Inorder Tree Traversal NEW_LINE DEDENT " NEW_LINE inorder ( root ) NEW_LINE fixPrevPtr . pre = None NEW_LINE head = BTToDLL ( root ) NEW_LINE print " NEW_LINE INDENT DLL Traversal NEW_LINE DEDENT " NEW_LINE printList ( head ) NEW_LINE |
Given a matrix of ' O ' and ' X ' , find the largest subsquare surrounded by ' X ' | Size of given matrix is N X N ; Initialize maxside with 0 ; Fill the dp matrix horizontally . for contiguous ' X ' increment the value of x , otherwise make it 0 ; Fill the dp matrix vertically . For contiguous ' X ' increment the value of y , otherwise make it 0 ; Now check , for every value of ( i , j ) if sub - square is possible , traverse back horizontally by value val , and check if vertical contiguous ' X ' enfing at ( i , j - val + 1 ) is greater than equal to val . Similarly , check if traversing back vertically , the horizontal contiguous ' X ' ending at ( i - val + 1 , j ) is greater than equal to val . ; Store the final answer in maxval ; Return the final answe . ; Driver code ; Function call | N = 6 NEW_LINE def maximumSubSquare ( arr ) : NEW_LINE INDENT dp = [ [ [ - 1 , - 1 ] for i in range ( 51 ) ] for j in range ( 51 ) ] NEW_LINE maxside = [ [ 0 for i in range ( 51 ) ] for j in range ( 51 ) ] NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == ' X ' ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT x = 0 NEW_LINE DEDENT dp [ i ] [ j ] [ 0 ] = x NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( arr [ j ] [ i ] == ' X ' ) : NEW_LINE INDENT y += 1 NEW_LINE DEDENT else : NEW_LINE INDENT y = 0 NEW_LINE DEDENT dp [ j ] [ i ] [ 1 ] = y NEW_LINE DEDENT DEDENT maxval = 0 NEW_LINE val = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT val = min ( dp [ i ] [ j ] [ 0 ] , dp [ i ] [ j ] [ 1 ] ) NEW_LINE if ( dp [ i ] [ j - val + 1 ] [ 1 ] >= val and dp [ i - val + 1 ] [ j ] [ 0 ] >= val ) : NEW_LINE INDENT maxside [ i ] [ j ] = val NEW_LINE DEDENT else : NEW_LINE INDENT maxside [ i ] [ j ] = 0 NEW_LINE DEDENT maxval = max ( maxval , maxside [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return maxval NEW_LINE DEDENT mat = [ [ ' X ' , ' O ' , ' X ' , ' X ' , ' X ' , ' X ' ] , [ ' X ' , ' O ' , ' X ' , ' X ' , ' O ' , ' X ' ] , [ ' X ' , ' X ' , ' X ' , ' O ' , ' O ' , ' X ' ] , [ ' O ' , ' X ' , ' X ' , ' X ' , ' X ' , ' X ' ] , [ ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' O ' ] , [ ' O ' , ' O ' , ' X ' , ' O ' , ' O ' , ' O ' ] ] NEW_LINE print ( maximumSubSquare ( mat ) ) NEW_LINE |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.