Open In App

Minimum exchange such that no two adjacent Matrix cells have same character

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number of exchanges
int MinimumExchange(vector<vector<char> >& mat)
{
    int n = mat.size();
    int m = mat[0].size();
    int a = 0, b = 0;
 
    // Loop to count the number of 'A' and 'B;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (mat[i][j] == 'A') {
                a++;
            }
            else {
                b++;
            }
        }
    }
 
    // Helper to find the count of exchanges
    // for the two cases
    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 the minimum number of exchanges
    return x;
}
 
// Driver code
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';
 
    // Function call
    int ans = MinimumExchange(matrix);
    cout << ans;
 
    return 0;
}


Java




// Java code to implement the approach;
import java.util.*;
 
interface fn {
  public int run(char x, char y);
}
class GFG
{
 
  // Function to find the minimum number of exchanges
  static int MinimumExchange(char[][] mat)
  {
    int n = mat.length;
    int m = mat[0].length;
    int a = 0, b = 0;
 
    // Loop to count the number of 'A' and 'B;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (mat[i][j] == 'A') {
          a++;
        }
        else {
          b++;
        }
      }
    }
 
    // Helper to find the count of exchanges
    // for the two cases
    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 the minimum number of exchanges
    return x;
  }
 
  // Driver Code
  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';
 
    // Function call
    int ans = MinimumExchange(matrix);
    System.out.println(ans);
  }
}
// This code is contributed by Karandeep1234


Python3




import sys
 
# Function to find the minimum number of exchanges
 
 
def MinimumExchange(mat):
    n = len(mat)
    m = len(mat[0])
    a = 0
    b = 0
 
    # Loop to count the number of 'A' and 'B;
    for i in range(n):
        for j in range(m):
            if mat[i][j] == 'A':
                a += 1
            else:
                b += 1
 
    # Helper to find the count of exchanges
    # for the two cases
    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 the minimum number of exchanges
    return x
 
 
# Driver code
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'
 
    # Function call
    ans = MinimumExchange(matrix)
    print(ans)


C#




using System;
 
class GFG {
 
    // Function to find the minimum number of exchanges
    static int MinimumExchange(char[, ] mat)
    {
        int n = mat.GetLength(0);
        int m = mat.GetLength(1);
        int a = 0, b = 0;
 
        // Loop to count the number of 'A' and 'B;
        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;
 
        // Helper to find the count of exchanges
        // for the two cases
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
 
                // Check the condition
                if (i % 2 == j % 2) {
                    if (mat[i, j] == 'B') {
 
                        // increment the cnt by 1
                        cnt++;
                    }
                }
                else {
 
                    // Check if mat[i, j] == 'A'
                    if (mat[i, j] == 'A') {
                        cnt++;
                    }
                }
            }
        }
 
        int x = int.MaxValue;
 
        // Check if n * m is odd and a > b
        if (((((n * m) & 1) != 0) && (a > b))
            || ((n * m) % 2 == 0)) {
 
            x = cnt / 2;
        }
        cnt = 0;
 
        // Again Iterate over the mat
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
 
                // Check if i % 2 == j % 2
                if (i % 2 == j % 2) {
                    if (mat[i, j] == 'A') {
 
                        // Increment the cnt by 1
                        cnt++;
                    }
                }
                else {
 
                    // Check if mat[i, j] == 'B'
                    if (mat[i, j] == 'B') {
 
                        // Increment the cnt by 1
                        cnt++;
                    }
                }
            }
        }
 
        // Check if n * m is odd and b > a
        if (((((n * m) & 1) != 0) && b > a)
            || ((n * m) % 2 == 0)) {
            x = Math.Min(x, cnt / 2);
        }
 
        // Return the minimum number of exchanges
        return x;
    }
 
    // Driver Code
    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';
 
        // Function call
        int ans = MinimumExchange(matrix);
        Console.WriteLine(ans);
    }
}


Javascript




<script>
    // JavaScript code to implement the approach
 
    const INT_MAX = 2147483647;
 
    // Function to find the minimum number of exchanges
    const MinimumExchange = (mat) => {
        let n = mat.length;
        let m = mat[0].length;
        let a = 0, b = 0;
 
        // Loop to count the number of 'A' and 'B;
        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';
 
 
    // Function call
    let ans = MinimumExchange(matrix);
    document.write(ans);
 
    // This code is contributed by rakeshsahni
 
</script>


Output

0

Time Complexity: O(N*M) to traverse the matrix
Auxiliary Space: O(1) because no extra memory is used.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads