Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths

Given a matrix mat[][] with N rows and M columns. The task is to find the minimum number of changes required in the matrix such that every path from top left to bottom right is a palindromic path. In a path only right and bottom movements are allowed from one cell to another cell.
Examples:

Input: mat[][] = {{1, 2}, {3, 1}} 
Output:
Explanation: 
Every path in the matrix from top left to bottom right is palindromic. 
Paths => {1, 2, 1}, {1, 3, 1}

Input: mat[][] = {{1, 2}, {3, 5}} 
Output:
Explanation: 
Only one change is required for the every path to be palindromic. 
That is => mat[1][1] = 1 
Paths => {1, 2, 1}, {1, 3, 1}

Approach: The key observation in the problem is that elements at the same distance from the front end or rear end are equal. Therefore, find all the elements at equal distance from (0, 0) and (N-1, M-1) and then make all of them equal in a minimum number of changes. Maintain a count variable to get the total number of changes. Below is the illustration of the approach: 

  • The distance possible from the top left and bottom right is 0 to N + M – 2.
  • Maintain two-pointers one at the top left that is the distance at 0 and another at N + M – 2.
  • Iterate over the matrix and for all distance maintain an hash-map of the elements of the matrix at the current distance.
  • Update the matrix elements with the minimum number of changes required.
  • Finally, increment the left distance by 1 and decrement the right distance by 1.

Below is the implementation of the above approach: 



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the 
// minimum number of changes required
// such that every path from top left 
// to the bottom right 
// are palindromic paths
  
#include <bits/stdc++.h>
using namespace std;
#define M 3
#define N 3
  
// Function to find the minimum number 
// of the changes required for the 
// every path to be palindromic
int minchanges(int mat[N][M])
{
    // count variable for 
    // maintaining total changes.
    int count = 0;
  
    // left and right variables for 
    // keeping distance values
    // from cell(0, 0) and 
    // (N-1, M-1) respectively.
    int left = 0, right = N + M - 2;
  
    while (left < right) {
  
        unordered_map<int, int> mp;
        int totalsize = 0;
  
        // Iterating over the matrix
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (i + j == left) {
                    mp[mat[i][j]]++;
                    totalsize++;
                }
                else if (i + j == right) {
                    mp[mat[i][j]]++;
                    totalsize++;
                }
            }
        }
  
        // Finding minimum number
        // of changes required.
        unordered_map<int
          int>::iterator itr = mp.begin();
        int changes = 0;
        for (; itr != mp.end(); itr++)
            changes = max(changes, itr->second);
  
        // Minimum no. of changes will 
        // be the the minimum no.
        // of different values and 
        // we will assume to
        // make them equals to value 
        // with maximum frequency element
        count += totalsize - changes;
          
        // Moving ahead with
        // greater distance
        left++;
        right--;
    }
    return count;
}
  
// Driven Code
int main()
{
    int mat[][M] = {
        { 1, 4, 1 },
        { 2, 5, 3 },
        { 1, 3, 1 }
    };
  
    cout << minchanges(mat);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the  
// minimum number of changes required 
// such that every path from top left  
// to the bottom right are palindromic 
// paths 
import java.io.*;
import java.util.*;
  
class GFG{
      
static final int M = 3;
static final int N = 3
  
// Function to find the minimum number 
// of the changes required for the 
// every path to be palindromic
static int minchanges(int[][] mat)
{
      
    // count variable for 
    // maintaining total changes.
    int count = 0;
  
    // left and right variables for 
    // keeping distance values
    // from cell(0, 0) and 
    // (N-1, M-1) respectively.
    int left = 0, right = N + M - 2;
  
    while (left < right)
    {
        Map<Integer, 
            Integer> mp = new HashMap<>();
              
        int totalsize = 0;
  
        // Iterating over the matrix
        for(int i = 0; i < N; i++) 
        {
            for(int j = 0; j < M; j++) 
            {
                if (i + j == left)
                {
                    mp.put(mat[i][j], 
                           mp.getOrDefault(
                           mat[i][j], 0) + 1);
                    totalsize++;
                }
                else if (i + j == right)
                {
                    mp.put(mat[i][j], 
                           mp.getOrDefault(
                           mat[i][j], 0) + 1);
                    totalsize++;
                }
            }
        }
  
        // Finding minimum number
        // of changes required.
        int changes = 0;
        for(Map.Entry<Integer,
                      Integer> itr : mp.entrySet())
            changes = Math.max(changes, 
                               itr.getValue());
  
        // Minimum no. of changes will 
        // be the the minimum no.
        // of different values and 
        // we will assume to
        // make them equals to value 
        // with maximum frequency element
        count += totalsize - changes;
          
        // Moving ahead with
        // greater distance
        left++;
        right--;
    }
    return count;
}
  
// Driver Code
public static void main (String[] args)
{
    int mat[][] = { { 1, 4, 1 },
                    { 2, 5, 3 },
                    { 1, 3, 1 } };
      
    System.out.println(minchanges(mat));
}
}
  
// This code is contributed by offbeat

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

#Python3 implementation to find the
#minimum number of changes required
#such that every path from top left
#to the bottom right
#are palindromic paths
M = 3
N = 3
  
#Function to find the minimum number
#of the changes required for the
#every path to be palindromic
def minchanges(mat):
    #count variable for
    #maintaining total changes.
    count = 0
  
    #left and right variables for
    #keeping distance values
    #from cell(0, 0) and
    #(N-1, M-1) respectively.
    left = 0
    right = N + M - 2
  
    while (left < right):
        mp={}
        totalsize = 0
  
        #Iterating over the matrix
        for i in range(N):
            for j in range(M):
                if (i + j == left):
                    mp[mat[i][j]] = 
                       mp.get(mat[i][j], 0) + 1
                    totalsize += 1
                elif (i + j == right):
                    mp[mat[i][j]] = 
                       mp.get(mat[i][j], 0) + 1
                    totalsize += 1
  
        #Finding minimum number
        #of changes required.
        changes = 0
        for itr in mp:
            changes = max(changes, mp[itr])
  
        #Minimum no. of changes will
        #be the the minimum no.
        #of different values and
        #we will assume to
        #make them equals to value
        #with maximum frequency element
        count += totalsize - changes
  
        #Moving ahead with
        #greater distance
        left += 1
        right -= 1
    return count
  
#Driver Code
if __name__ == '__main__':
    mat= [[1, 4, 1],
          [2, 5, 3],
          [1, 3, 1]]
    print(minchanges(mat))
  
# This code is contributed by Mohit Kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find the 
// minimum number of changes required 
// such that every path from top left 
// to the bottom right are palindromic 
// paths 
using System;
using System.Collections; 
using System.Collections.Generic; 
  
class GFG{
      
static int M = 3;
static int N = 3; 
  
// Function to find the minimum number 
// of the changes required for the 
// every path to be palindromic
static int minchanges(int[,] mat)
{
      
    // count variable for 
    // maintaining total changes.
    int count = 0;
  
    // left and right variables for 
    // keeping distance values
    // from cell(0, 0) and 
    // (N-1, M-1) respectively.
    int left = 0, right = N + M - 2;
  
    while (left < right)
    {
        Dictionary<int,
                   int> mp = new Dictionary<int,
                                            int>();
        int totalsize = 0;
  
        // Iterating over the matrix
        for(int i = 0; i < N; i++) 
        {
            for(int j = 0; j < M; j++) 
            {
                if (i + j == left)
                {
                    if(mp.ContainsKey(mat[i, j]))
                    {
                        mp[mat[i, j]]++; 
                    }
                    else
                    {
                        mp[mat[i, j]] = 1; 
                    }
                    totalsize++;
                }
                else if (i + j == right)
                {
                    if(mp.ContainsKey(mat[i, j]))
                    {
                        mp[mat[i, j]]++; 
                    }
                    else
                    {
                        mp[mat[i, j]] = 1; 
                    }
                    totalsize++;
                }
            }
        }
  
        // Finding minimum number
        // of changes required.
        int changes = 0;
        foreach(KeyValuePair<int, int> itr in mp) 
        
            changes = Math.Max(changes, 
                               itr.Value); 
        
      
        // Minimum no. of changes will 
        // be the the minimum no.
        // of different values and 
        // we will assume to
        // make them equals to value 
        // with maximum frequency element
        count += totalsize - changes;
          
        // Moving ahead with
        // greater distance
        left++;
        right--;
    }
    return count;
}
      
// Driver Code
public static void Main(string[] args)
{
    int [,]mat = { { 1, 4, 1 },
                   { 2, 5, 3 },
                   { 1, 3, 1 } };
  
    Console.Write(minchanges(mat));
}
}
  
// This code is contributed by rutvik_56

chevron_right


Output: 

2

Performance Analysis: 

  • Time Complexity: O(N3)
  • Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.