Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B
Last Updated :
09 Jul, 2021
Given two binary matrices, A[][] and B[][] of size N×M, the task is to find the minimum number of swaps of the elements of matrix A, needed to convert matrix A into matrix B. If it is impossible to do so then print "-1".
Examples :
Input: A[][] = {{1, 1, 0}, {0, 0, 1}, {0, 1, 0}}, B[][] = {{0, 0, 1}, {0, 1, 0}, {1, 1, 0}}
Output: 3
Explanation:
One possible way to convert matrix A into B is:
- Swap the element A[0][0] with A[0][2]. Thereafter the matrix A modifies to {{ 0, 1, 1}, {0, 0, 1}, {0, 1, 0}}.
- Swap the element A[0][1] with A[1][1]. Thereafter the matrix A modifies to {{ 0, 0, 1}, {0, 1, 1}, {0, 1, 0}}.
- Swap the element A[1][2] with A[2][0]. Thereafter the matrix A modifies to {{ 0, 0, 1}, {0, 1, 0}, {1, 1, 0}}.
Therefore, the total number of moves needed is 3 and also it is the minimum number of moves needed.
Input: A[][] = {{1, 1}, {0, 1}, {1, 0}, {0, 0}}, B[][] = {{1, 1}, {1, 1}, {0, 1}, {0, 0}}
Output: -1
Naive Approach: This problem can be solved using Hashing. To convert matrix A to B by only swaps, the count of set bits and unset bits in both the matrices must be same. So first check if the set bits and unset bits in A is same as in B or not. If yes, then find the number of positions where element in A is not same as element in B. This will be the final count.
Efficient Approach: The above approach can be further space optimized, with the help of observation that count the number of elements such that A[i][j] = 0 and B[i][j] = 1 and number of elements such that A[i][j] = 1 and B[i][j] = 0 must be equal and the minimum number of moves needed is equal to the count obtained. Follow the steps below to solve the problem:
- Initialize two variable, say count10 and count01 which count the number of elements such that A[i][j] = 1 and B[i][j] = 0 and number of elements such that A{i][j] = 0 and B[i][j] = 1 respectively.
- Iterate over the range [0, N-1] using the variable i and perform the following steps:
- Iterate over the range [0, M-1] using the variable j and if A[i][j] = 1 and B[i][j] = 0 then increment the count10 by 1. Else, if A[i][j] = 0 and B[i][j] = 1 then increment the count01 by 1.
- If count01 is equal to count10, then print the value of count01 as the answer. Otherwise, print -1 as the answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the minimum number
// of swaps required to convert matrix
// A to matrix B
int minSwaps(int N, int M, vector<vector<int> >& A,
vector<vector<int> >& B)
{
// Stores number of cells such that
// matrix A contains 0 and matrix B
// contains 1
int count01 = 0;
// Stores number of cells such that
// matrix A contains 1 and matrix B
// contains 0
int count10 = 0;
// Iterate over the range [0, N-1]
for (int i = 0; i < N; i++) {
// Iterate over the range [0, M-1]
for (int j = 0; j < M; j++) {
if (A[i][j] != B[i][j]) {
// If A[i][j] = 1 and B[i][j] = 0
if (A[i][j] == 1)
count10++;
// If A[i][j] = 0 and B[i][j] = 1
else
count01++;
}
}
}
// If count01 is equal to count10
if (count01 == count10)
return count01;
// Otherwise,
else
return -1;
}
// Driver Code
int main()
{
vector<vector<int> > A
= { { 1, 1, 0 }, { 0, 0, 1 }, { 0, 1, 0 } };
vector<vector<int> > B
= { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 1, 0 } };
int N = A.size();
int M = B[0].size();
cout << minSwaps(N, M, A, B);
}
Java
// Java program for the above approach
public class MyClass
{
// Function to count the minimum number
// of swaps required to convert matrix
// A to matrix B
public static int minSwaps(int N, int M, int A[][], int B[][])
{
// Stores number of cells such that
// matrix A contains 0 and matrix B
// contains 1
int count01 = 0;
// Stores number of cells such that
// matrix A contains 1 and matrix B
// contains 0
int count10 = 0;
// Iterate over the range [0, N-1]
for (int i = 0; i < N; i++) {
// Iterate over the range [0, M-1]
for (int j = 0; j < M; j++) {
if (A[i][j] != B[i][j]) {
// If A[i][j] = 1 and B[i][j] = 0
if (A[i][j] == 1)
count10++;
// If A[i][j] = 0 and B[i][j] = 1
else
count01++;
}
}
}
// If count01 is equal to count10
if (count01 == count10)
return count01;
// Otherwise,
else
return -1;
}
// Driver Code
public static void main(String args[])
{
int [][] A = { { 1, 1, 0 }, { 0, 0, 1 }, { 0, 1, 0 } };
int [][] B = { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 1, 0 } };
int N = A.length;
int M = B[0].length;
System.out.println(minSwaps(N, M, A, B));
}}
// This code is contributed by SoumikMondal
Python3
# Python3 program for the above approach
# Function to count the minimum number
# of swaps required to convert matrix
# A to matrix B
def minSwaps(N, M, A, B):
# Stores number of cells such that
# matrix A contains 0 and matrix B
# contains 1
count01 = 0
# Stores number of cells such that
# matrix A contains 1 and matrix B
# contains 0
count10 = 0
# Iterate over the range[0, N-1]
for i in range(0, N):
# Iterate over the range[0, M-1]
for j in range(0, M):
if (A[i][j] != B[i][j]):
# If A[i][j] = 1 and B[i][j] = 0
if (A[i][j] == 1):
count10 += 1
# If A[i][j] = 0 and B[i][j] = 1
else:
count01 += 1
# If count01 is equal to count10
if (count01 == count10):
return count01
# Otherwise,
else:
return -1
# Driver Code
A = [ [ 1, 1, 0 ], [ 0, 0, 1 ], [ 0, 1, 0 ] ]
B = [ [ 0, 0, 1 ], [ 0, 1, 0 ], [ 1, 1, 0 ] ]
N = len(A)
M = len(B[0])
print(minSwaps(N, M, A, B))
# This code is contributed by amreshkumar3
JavaScript
<script>
// JavaScript program for the above approach
// Function to count the minimum number
// of swaps required to convert matrix
// A to matrix B
function minSwaps(N, M, A, B)
{
// Stores number of cells such that
// matrix A contains 0 and matrix B
// contains 1
let count01 = 0;
// Stores number of cells such that
// matrix A contains 1 and matrix B
// contains 0
let count10 = 0;
// Iterate over the range [0, N-1]
for (let i = 0; i < N; i++) {
// Iterate over the range [0, M-1]
for (let j = 0; j < M; j++) {
if (A[i][j] != B[i][j]) {
// If A[i][j] = 1 and B[i][j] = 0
if (A[i][j] == 1)
count10++;
// If A[i][j] = 0 and B[i][j] = 1
else
count01++;
}
}
}
// If count01 is equal to count10
if (count01 == count10)
return count01;
// Otherwise,
else
return -1;
}
// Driver Code
let A
= [[1, 1, 0], [0, 0, 1], [0, 1, 0]];
let B
= [[0, 0, 1], [0, 1, 0], [1, 1, 0]];
let N = A.length;
let M = B[0].length;
document.write(minSwaps(N, M, A, B));
// This code is contributed by Potta Lokesh
</script>
C#
// C# program for the above approach
using System;
class GFG {
// Function to count the minimum number
// of swaps required to convert matrix
// A to matrix B
public static int minSwaps(int N, int M, int[,] A, int[,] B)
{
// Stores number of cells such that
// matrix A contains 0 and matrix B
// contains 1
int count01 = 0;
// Stores number of cells such that
// matrix A contains 1 and matrix B
// contains 0
int count10 = 0;
// Iterate over the range [0, N-1]
for (int i = 0; i < N; i++) {
// Iterate over the range [0, M-1]
for (int j = 0; j < M; j++) {
if (A[i,j] != B[i, j]) {
// If A[i][j] = 1 and B[i][j] = 0
if (A[i, j] == 1)
count10++;
// If A[i][j] = 0 and B[i][j] = 1
else
count01++;
}
}
}
// If count01 is equal to count10
if (count01 == count10)
return count01;
// Otherwise,
else
return -1;
}
// Driver code
public static void Main (String[] args)
{
int [,] A = { { 1, 1, 0 }, { 0, 0, 1 }, { 0, 1, 0 } };
int [,] B = { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 1, 0 } };
int N = A.GetLength(0);
int M = 3;
Console.Write(minSwaps(N, M, A, B));
}
}
Time Complexity: O(N*M).
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read