Celdas mínimas que se deben voltear para obtener una subarray de 2 * 2 con elementos iguales

Dada una array de tamaño M * N , la tarea es encontrar el recuento del número mínimo de celdas que se deben voltear para que haya al menos una subarray de tamaño 2*2 con todos los elementos iguales.
Ejemplos: 
 

Entrada: mat[] = {“00000”, “10111”, “00000”, “11111”} 
Salida:
Una de las posibles subarray podría ser {{0, 0}, {1, 0}} 
donde solo una el elemento tiene que ser volteado.
Entrada: mat[] = {“0101”, “0101”, “0101”} 
Salida:
 

Enfoque: para cada subarray de tamaño 2*2, cuente el número de 0 y el número de 1 en ella y el mínimo de estos dos será el número de vueltas necesarias para obtener la array con todos los elementos iguales. El mínimo de este valor para todas las subarrays es la respuesta requerida.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimum flips
// required such that the submatrix from
// mat[i][j] to mat[i + 1][j + 1]
// contains all equal elements
int minFlipsSub(string mat[], int i, int j)
{
    int cnt0 = 0, cnt1 = 0;
 
    if (mat[i][j] == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i][j + 1] == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i + 1][j] == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i + 1][j + 1] == '1')
        cnt1++;
    else
        cnt0++;
 
    return min(cnt0, cnt1);
}
 
// Function to return the minimum number
// of slips required such that the matrix
// contains at least a single submatrix
// of size 2*2 with all equal elements
int minFlips(string mat[], int r, int c)
{
 
    // To store the result
    int res = INT_MAX;
 
    // For every submatrix of size 2*2
    for (int i = 0; i < r - 1; i++) {
        for (int j = 0; j < c - 1; j++) {
 
            // Update the count of flips required
            // for the current submatrix
            res = min(res, minFlipsSub(mat, i, j));
        }
    }
 
    return res;
}
 
// Driver code
int main()
{
    string mat[] = { "0101", "0101", "0101" };
    int r = sizeof(mat) / sizeof(string);
    int c = mat[0].length();
 
    cout << minFlips(mat, r, c);
 
    return 0;
}

Java

// Java implementation of the approach
class GFG
{
 
// Function to return the minimum flips
// required such that the submatrix from
// mat[i][j] to mat[i + 1][j + 1]
// contains all equal elements
static int minFlipsSub(String mat[], int i, int j)
{
    int cnt0 = 0, cnt1 = 0;
 
    if (mat[i].charAt(j) == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i].charAt(j+1) == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i + 1].charAt(j) == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i + 1].charAt(j+1) == '1')
        cnt1++;
    else
        cnt0++;
 
    return Math.min(cnt0, cnt1);
}
 
// Function to return the minimum number
// of slips required such that the matrix
// contains at least a single submatrix
// of size 2*2 with all equal elements
static int minFlips(String mat[], int r, int c)
{
    // To store the result
    int res = Integer.MAX_VALUE;
 
    // For every submatrix of size 2*2
    for (int i = 0; i < r - 1; i++)
    {
        for (int j = 0; j < c - 1; j++)
        {
            // Update the count of flips required
            // for the current submatrix
            res = Math.min(res, minFlipsSub(mat, i, j));
        }
    }
    return res;
}
 
// Driver code
public static void main(String[] args)
{
    String mat[] = { "0101", "0101", "0101" };
    int r = mat.length;
    int c = mat[0].length();
 
    System.out.print(minFlips(mat, r, c));
}
}
 
// This code is contributed by 29AjayKumar

Python 3

# Python 3 implementation of the approach
import sys
 
# Function to return the minimum flips
# required such that the submatrix from
# mat[i][j] to mat[i + 1][j + 1]
# contains all equal elements
def minFlipsSub(mat, i, j):
    cnt0 = 0
    cnt1 = 0
 
    if (mat[i][j] == '1'):
        cnt1 += 1
    else:
        cnt0 += 1
 
    if (mat[i][j + 1] == '1'):
        cnt1 += 1
    else:
        cnt0 += 1
 
    if (mat[i + 1][j] == '1'):
        cnt1 += 1
    else:
        cnt0 += 1
 
    if (mat[i + 1][j + 1] == '1'):
        cnt1 += 1
    else:
        cnt0 += 1
 
    return min(cnt0, cnt1)
 
# Function to return the minimum number
# of slips required such that the matrix
# contains at least a single submatrix
# of size 2*2 with all equal elements
def minFlips(mat, r, c):
     
    # To store the result
    res = sys.maxsize
 
    # For every submatrix of size 2*2
    for i in range(r - 1):
        for j in range(c - 1):
             
            # Update the count of flips required
            # for the current submatrix
            res = min(res, minFlipsSub(mat, i, j))
 
    return res
 
# Driver code
if __name__ == '__main__':
    mat = ["0101", "0101", "0101"]
    r = len(mat)
    c = len(mat[0])
 
    print(minFlips(mat, r, c))
     
# This code is contributed by Surendra_Gangwar

C#

// C# implementation of the approach
using System;
 
class GFG
{
 
// Function to return the minimum flips
// required such that the submatrix from
// mat[i,j] to mat[i + 1,j + 1]
// contains all equal elements
static int minFlipsSub(String []mat,
                       int i, int j)
{
    int cnt0 = 0, cnt1 = 0;
 
    if (mat[i][j] == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i][j + 1] == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i + 1][j] == '1')
        cnt1++;
    else
        cnt0++;
 
    if (mat[i + 1][j + 1] == '1')
        cnt1++;
    else
        cnt0++;
 
    return Math.Min(cnt0, cnt1);
}
 
// Function to return the minimum number
// of slips required such that the matrix
// contains at least a single submatrix
// of size 2*2 with all equal elements
static int minFlips(String []mat,
                    int r, int c)
{
    // To store the result
    int res = int.MaxValue;
 
    // For every submatrix of size 2*2
    for (int i = 0; i < r - 1; i++)
    {
        for (int j = 0; j < c - 1; j++)
        {
            // Update the count of flips required
            // for the current submatrix
            res = Math.Min(res, minFlipsSub(mat, i, j));
        }
    }
    return res;
}
 
// Driver code
public static void Main(String[] args)
{
    String []mat = { "0101", "0101", "0101" };
    int r = mat.Length;
    int c = mat.GetLength(0);
 
    Console.Write(minFlips(mat, r, c));
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
// javascript implementation of the approach   
// Function to return the minimum flips
    // required such that the submatrix from
    // mat[i][j] to mat[i + 1][j + 1]
    // contains all equal elements
    function minFlipsSub( mat , i , j)
    {
        var cnt0 = 0, cnt1 = 0;
 
        if (mat[i].charAt(j) == '1')
            cnt1++;
        else
            cnt0++;
 
        if (mat[i].charAt(j + 1) == '1')
            cnt1++;
        else
            cnt0++;
 
        if (mat[i + 1].charAt(j) == '1')
            cnt1++;
        else
            cnt0++;
 
        if (mat[i + 1].charAt(j + 1) == '1')
            cnt1++;
        else
            cnt0++;
 
        return Math.min(cnt0, cnt1);
    }
 
    // Function to return the minimum number
    // of slips required such that the matrix
    // contains at least a single submatrix
    // of size 2*2 with all equal elements
    function minFlips(mat , r , c)
    {
     
        // To store the result
        var res = Number.MAX_VALUE;
 
        // For every submatrix of size 2*2
        for (i = 0; i < r - 1; i++)
        {
            for (j = 0; j < c - 1; j++)
            {
             
                // Update the count of flips required
                // for the current submatrix
                res = Math.min(res, minFlipsSub(mat, i, j));
            }
        }
        return res;
    }
 
    // Driver code
        var mat = [ "0101", "0101", "0101" ];
        var r = mat.length;
        var c = mat[0].length;
 
        document.write(minFlips(mat, r, c));
         
// This code is contributed by Rajput-Ji
</script>
Producción: 

2

 

Complejidad temporal: O(r * c)

Espacio Auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por akhand_mishra y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *