VOOZH about

URL: https://www.geeksforgeeks.org/dsa/move-matrix-elements-given-direction-add-elements-value/

⇱ Move matrix elements in given direction and add elements with same value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Move matrix elements in given direction and add elements with same value

Last Updated : 19 Aug, 2022

Given a matrix m[ ][ ] of size n x n consisting of integers and given a character 'x' indicating the direction. Value of 'x' can be 'u', 'd', 'l', 'r' indicating Up, Down, Left, Right correspondingly. The task is to move the element to given direction such that the consecutive elements having same value are added into single value and shift the rest element. Also, shift the element if the next element in given direction is 0. 

For example : 
Consider x = 'l' and matrix m[][], 
32 3 3 
0 0 1 
10 10 8
After adding 3 in first row, 10 in third row and moving 1 in second row, 
Matrix will become 
32 6 0 
1 0 0 
20 8 0

Examples :  

Input : x = 'l'
m[][] = { { 32, 3, 3, 3, 3 },
 { 0, 0, 1, 0, 0 },
 { 10, 10, 8, 1, 2},
 { 0, 0, 0, 0, 1},
 { 4, 5, 6, 7, 8 } }
Output :
32 6 6 0 0
1 0 0 0 0
20 8 1 2 0
1 0 0 0 0 0
4 5 6 7 8

Input : x = 'u'
m[][] = { { 10, 3, 32 },
 { 10, 0, 96 },
 { 5, 32, 96 } }
Output :
20 3 32
5 32 192
0 0 0

Approach : The idea is to traverse each row or column (depending on given direction) from side x of row or column towards x' (opposite of x). For example, if the given value of x is 'l' (left) then start scanning each row from left side to right. While traversing, store row or column element in the temporary 1-D array (say temp[]) by skipping elements having value 0 and sum of the consecutive element if they have equal value. After that, start copying the temporary array temp[0..k] to the current row or column from the x side (of row or column) to x' (opposite of x) and fill reset of the element by 0.

Let, x = 'l' i.e move towards left. So, start copying each row from left most index to right most index of the row and store in temporary array with processing of ignoring 0s and adding two consecutive element into one if they have same value. Below is the illustration for row 1,  

👁 Image

Now, for each, copy temporary array to current row from left most index to right most index. Below is illustration for row 1,  

👁 Image

Below is the implementation of this approach : 


Output: 
32 6 6 0 0 
1 0 0 0 0 
20 8 1 2 0 
1 0 0 0 0 
4 5 6 7 8

 

Time Complexity: O(n2)
Auxiliary Space: O(n), since n extra space has been taken.

Comment