Given two matrices A and B of order n*m. The task is to find the required number of transformation steps so that both matrices became equal, print -1 if it is not possible.
Transformation step is as:
i) Select any one matrix out of two matrices.
ii) Choose either row/column of selected matrix.
iii) Increment every element of select row/column by 1.
Input : A: 1 1 1 1 B: 1 2 3 4 Output : 3 Explaination : 1 1 -> 1 2 -> 1 2 -> 1 2 1 1 -> 1 2 -> 2 3 -> 3 4 Input : A: 1 1 1 0 B: 1 2 3 4 Output : -1 Explaination : No transformation will make A and B equal.
The key steps behind the solution of this problem are:
-> Incrementing any row of A is same as decrementing the same row of B. So, we can have the solution after having the transformation on only one matrix either incrementing or decrementing.
So make A[i][j] = A[i][j] - B[i][j]. For example, If given matrices are, A : 1 1 1 1 B : 1 2 3 4 After subtraction, A becomes, A : 0 -1 -2 -3
-> For every transformation either 1st row/ 1st column element necessarily got changed, same is true for other i-th row/column.
-> If ( A[i][j] – A[i] – A[j] + A != 0) then no solution exists.
-> Elements of 1st row and 1st column only leads to result.
// Update matrix A // so that only A // has to be transformed for (i = 0; i < n; i++) for (j = 0; j < m; j++) A[i][j] -= B[i][j]; // Check necessary condition // For condition for // existence of full transformation for (i = 1; i < n; i++) for (j = 1; j < m; j++) if (A[i][j] - A[i] - A[j] + A != 0) return -1; // If transformation is possible // calculate total transformation result = 0; for (i = 0; i < n; i++) result += abs(A[i]) for (j = 0; j < m; j++) result += abs(A[j] - A); return abs(result);
Time Complexity: O (n*m)
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum size square sub-matrix with all 1s
- Print a given matrix in spiral form
- Search in a row wise and column wise sorted matrix
- A Boolean Matrix Question
- Matrix Chain Multiplication | DP-8
- Find the row with maximum number of 1s
- Print unique rows in a given boolean matrix
- Inplace (Fixed space) M x N size matrix transpose | Updated
- Find the number of islands | Set 1 (Using DFS)
- Maximum sum rectangle in a 2D matrix | DP-27
- Zigzag (or diagonal) traversal of Matrix
- Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
- Print all possible paths from top left to bottom right of a mXn matrix
- Count all possible paths from top left to bottom right of a mXn matrix
- Printing brackets in Matrix Chain Multiplication Problem