Minimum exchange such that no two adjacent Matrix cells have same character
Last Updated :
24 Jan, 2023
Given a matrix of size N * M. Every cell of the matrix contains either ‘A’ or ‘B’. Exchange is defined as swapping the characters between two cells. The task is to find the minimum number of exchanges needed to rearrange the given matrix such that no adjacent cell contains the same characters.
Note: Two cells are adjacent if they share one of their common sides (left, right, top, or bottom if exists).
Examples:
Input: matrix = {{A, A, B, A}, {B, A, B, A}, {B, B, A, B}}
Output: 2
Explanation: Minimum number of cells whose
characters got changed are 4 (indexes: ((0, 1), (0, 2),
(0, 3), (2, 0))). The final matrix is:
A B A B
B A B A
A B A B
Here 2 exchange are done so answer is 2.
Input: matrix = {{A, B}, {B, A}}
Output: 0
Explanation: No two adjacent cell contains same character.
Approach: The problem can be solved based on the following idea:
The idea is to use odd and even places, put ‘A’ at odd(i.e- row+column is odd) and ‘B’ at even(i.e- row+column is even) places, and calculate the number of exchanges required according to the initial matrix and again use vice versa ( i.e:- B at odd and A at even) and then return in which one required exchanges is minimum.
Follow the steps below to solve the problem:
- Initialize two variables temp1 and temp2 and assume the number of exchanges is temp1 for ‘A’ at even places and temp2 for ‘A’ at odd places.
- Run a nested loop for every column of each row and check whether it is the odd place or even place.
- If it’s an even place and it has ‘A’ then increase temp2.
- Else increase temp1 and check accordingly for odd places also.
- At the end of loops return the minimum of temp1 and temp2.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int MinimumExchange(vector<vector< char > >& mat)
{
int n = mat.size();
int m = mat[0].size();
int a = 0, b = 0;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
if (mat[i][j] == 'A' ) {
a++;
}
else {
b++;
}
}
}
auto helper = [&]( char x, char y) {
int cnt = 0;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
if (i % 2 == j % 2) {
if (mat[i][j] == x) {
cnt++;
}
}
else {
if (mat[i][j] == y) {
cnt++;
}
}
}
}
return cnt / 2;
};
int x = INT_MAX;
if ((((n * m) & 1) && a > b) || ((n * m) % 2 == 0)) {
x = helper( 'B' , 'A' );
}
if ((((n * m) & 1) && b > a) || ((n * m) % 2 == 0)) {
x = min(x, helper( 'A' , 'B' ));
}
return x;
}
int main()
{
int N = 2, M = 2;
vector<vector< char > > matrix(N, vector< char >(M, 'x' ));
matrix[0][0] = 'A' ;
matrix[0][1] = 'B' ;
matrix[1][0] = 'B' ;
matrix[1][1] = 'A' ;
int ans = MinimumExchange(matrix);
cout << ans;
return 0;
}
|
Java
import java.util.*;
interface fn {
public int run( char x, char y);
}
class GFG
{
static int MinimumExchange( char [][] mat)
{
int n = mat.length;
int m = mat[ 0 ].length;
int a = 0 , b = 0 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < m; j++) {
if (mat[i][j] == 'A' ) {
a++;
}
else {
b++;
}
}
}
fn helper = (x, y) ->
{
int cnt = 0 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < m; j++) {
if (i % 2 == j % 2 ) {
if (mat[i][j] == x) {
cnt++;
}
}
else {
if (mat[i][j] == y) {
cnt++;
}
}
}
}
return cnt / 2 ;
};
int x = Integer.MAX_VALUE;
if (((((n * m) & 1 ) != 0 ) && (a > b))
|| ((n * m) % 2 == 0 )) {
x = helper.run( 'B' , 'A' );
}
if (((((n * m) & 1 ) != 0 ) && b > a)
|| ((n * m) % 2 == 0 )) {
x = Math.min(x, helper.run( 'A' , 'B' ));
}
return x;
}
public static void main(String[] args)
{
int N = 2 , M = 2 ;
char [][] matrix = new char [N][M];
matrix[ 0 ][ 0 ] = 'A' ;
matrix[ 0 ][ 1 ] = 'B' ;
matrix[ 1 ][ 0 ] = 'B' ;
matrix[ 1 ][ 1 ] = 'A' ;
int ans = MinimumExchange(matrix);
System.out.println(ans);
}
}
|
Python3
import sys
def MinimumExchange(mat):
n = len (mat)
m = len (mat[ 0 ])
a = 0
b = 0
for i in range (n):
for j in range (m):
if mat[i][j] = = 'A' :
a + = 1
else :
b + = 1
def helper(x, y):
cnt = 0
for i in range (n):
for j in range (m):
if i % 2 = = j % 2 :
if mat[i][j] = = x:
cnt + = 1
else :
if mat[i][j] = = y:
cnt + = 1
return cnt / / 2
x = sys.maxsize
if ((((n * m) & 1 ) and a > b) or ((n * m) % 2 = = 0 )):
x = helper( 'B' , 'A' )
if ((((n * m) & 1 ) and b > a) or ((n * m) % 2 = = 0 )):
x = min (x, helper( 'A' , 'B' ))
return x
if __name__ = = '__main__' :
N = 2
M = 2
matrix = [[ 'x' for j in range (M)] for i in range (N)]
matrix[ 0 ][ 0 ] = 'A'
matrix[ 0 ][ 1 ] = 'B'
matrix[ 1 ][ 0 ] = 'B'
matrix[ 1 ][ 1 ] = 'A'
ans = MinimumExchange(matrix)
print (ans)
|
C#
using System;
class GFG {
static int MinimumExchange( char [, ] mat)
{
int n = mat.GetLength(0);
int m = mat.GetLength(1);
int a = 0, b = 0;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
if (mat[i, j] == 'A' ) {
a++;
}
else {
b++;
}
}
}
int cnt = 0;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
if (i % 2 == j % 2) {
if (mat[i, j] == 'B' ) {
cnt++;
}
}
else {
if (mat[i, j] == 'A' ) {
cnt++;
}
}
}
}
int x = int .MaxValue;
if (((((n * m) & 1) != 0) && (a > b))
|| ((n * m) % 2 == 0)) {
x = cnt / 2;
}
cnt = 0;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
if (i % 2 == j % 2) {
if (mat[i, j] == 'A' ) {
cnt++;
}
}
else {
if (mat[i, j] == 'B' ) {
cnt++;
}
}
}
}
if (((((n * m) & 1) != 0) && b > a)
|| ((n * m) % 2 == 0)) {
x = Math.Min(x, cnt / 2);
}
return x;
}
public static void Main( string [] args)
{
int N = 2, M = 2;
char [, ] matrix = new char [N, M];
matrix[0, 0] = 'A' ;
matrix[0, 1] = 'B' ;
matrix[1, 0] = 'B' ;
matrix[1, 1] = 'A' ;
int ans = MinimumExchange(matrix);
Console.WriteLine(ans);
}
}
|
Javascript
<script>
const INT_MAX = 2147483647;
const MinimumExchange = (mat) => {
let n = mat.length;
let m = mat[0].length;
let a = 0, b = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (mat[i][j] == 'A ') {
a++;
}
else {
b++;
}
}
}
// Helper to find the count of exchanges
// for the two cases
const helper = (x, y) => {
let cnt = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (i % 2 == j % 2) {
if (mat[i][j] == x) {
cnt++;
}
}
else {
if (mat[i][j] == y) {
cnt++;
}
}
}
}
return parseInt(cnt / 2);
};
let x = INT_MAX;
if ((((n * m) & 1) && a > b) || ((n * m) % 2 == 0)) {
x = helper(' B ', ' A ');
}
if ((((n * m) & 1) && b > a) || ((n * m) % 2 == 0)) {
x = Math.min(x, helper(' A ', ' B '));
}
// Return the minimum number of exchanges
return x;
}
// Driver code
let N = 2, M = 2;
let matrix = new Array(N).fill(' x ').map(() => new Array(M).fill(' x '))
matrix[0][0] = ' A ';
matrix[0][1] = ' B ';
matrix[1][0] = ' B ';
matrix[1][1] = ' A';
let ans = MinimumExchange(matrix);
document.write(ans);
</script>
|
Time Complexity: O(N*M) to traverse the matrix
Auxiliary Space: O(1) because no extra memory is used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...