Minimice el costo para llegar a la esquina inferior derecha de una Array usando operaciones dadas

Dada una array grid[][] de tamaño N x N , la tarea es encontrar el costo mínimo requerido para alcanzar la esquina inferior derecha de la array desde la esquina superior izquierda, donde el costo de moverse a una nueva celda es [S /2] + K , donde S es la puntuación en el índice anterior y K es el elemento de array en el índice actual. 
Nota: Aquí, [X] es el entero más grande que no excede X .

Ejemplos:

Entrada: grid[][] = {{ 0, 3, 9, 6}, {1, 4, 4, 5}, {8, 2, 5, 4}, {1, 8, 5, 9}}
Salida : 12
Explicación:  Uno de los posibles conjuntos de movimientos es el siguiente 0 -> 1 -> 4 -> 4 -> 7 -> 7 -> 12.

 Entrada: g rid[][] = {{0, 82, 2, 6, 7}, {4, 3, 1, 5, 21}, {6, 4, 20, 2, 8}, {6, 6 , 64, 1, 8}, {1, 65, 1, 6, 4}}
Salida: 7

Enfoque: siga los pasos a continuación para resolver el problema:

  • Haga que el primer elemento de la array sea cero .
  • Traverse en el rango [0, N-1] :
    • Inicialice una lista, diga moveList y agregue los movimientos i y j .
    • Inicialice otra lista, diga posibles formas y añada moveList en ella.
    • Inicialice una lista, por ejemplo, possibleWaysSum, inicialmente como una lista vacía.
    • Recorra la lista de vías posibles :
      • Atraviesa la moveList adjunta :
        • Compruebe si el movimiento es igual a i, luego actualice i = i + 1.
        • De lo contrario, actualice j = j + 1 .
        • Inicialice una variable, diga tempSum. Establezca tempSum = tempSum + grid[i][j] .
      • Agregue tempSum en la lista de vías posibles después del ciclo.
  • Imprima el costo mínimo de possibleWaysSum como salida.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
vector<vector<char> > possibleWays;
 
// Returns true if str[curr] does not matches with any
// of the characters after str[start]
bool shouldSwap(char str[], int start, int curr)
{
  for (int i = start; i < curr; i++) {
    if (str[i] == str[curr]) {
      return false;
    }
  }
  return true;
}
 
// Function for the swap
void swap(char str[], int i, int j)
{
  char c = str[i];
  str[i] = str[j];
  str[j] = c;
}
 
// Prints all distinct permutations in str[0..n-1]
void findPermutations(char str[], int index, int n)
{
  if (index >= n) {
    vector<char> l;
    for (int i = 0; i < n; i++)
      l.push_back(str[i]);
    possibleWays.push_back(l);
    return;
  }
 
  for (int i = index; i < n; i++) {
 
    // Proceed further for str[i] only if it
    // doesn't match with any of the characters
    // after str[index]
    bool check = shouldSwap(str, index, i);
    if (check) {
      swap(str, index, i);
      findPermutations(str, index + 1, n);
      swap(str, index, i);
    }
  }
}
 
// Function to print the minimum cost
void minCost(int grid[][5], int N)
{
 
  vector<char> moveList;
 
  // Making top-left value 0
  // implicitly to generate list of moves
  grid[0][0] = 0;
  vector<int> possibleWaysSum;
 
  for (int k = 0; k < N - 1; k++) {
 
    moveList.push_back('i');
    moveList.push_back('j');
 
    possibleWays.clear();
 
    // Convert into set to make only unique values
    int n = moveList.size();
    char str[n];
    for (int i = 0; i < n; i++)
      str[i] = moveList[i];
 
    // To store the unique permutation of moveList
    // into the possibleWays
    findPermutations(str, 0, n);
    possibleWaysSum.clear();
 
    // Traverse the list
    for (vector<char> way : possibleWays) {
      int i = 0, j = 0, tempSum = 0;
      for (char move : way) {
        if (move == 'i') {
          i += 1;
        }
        else {
          j += 1;
        }
 
        // Stores cost according to given
        // conditions
        tempSum = (int)(floor(tempSum / 2))
          + grid[i][j];
      }
      possibleWaysSum.push_back(tempSum);
    }
  }
 
  // Print the minimum possible cost
  int ans = possibleWaysSum[0];
  for (int i = 1; i < possibleWaysSum.size(); i++)
    ans = min(ans, possibleWaysSum[i]);
 
  cout << ans;
}
 
// Driven Program
int main()
{
   
  // Size of the grid
  int N = 4;
 
  // Given grid[][]
  int grid[][5] = { { 0, 3, 9, 6 },
                   { 1, 4, 4, 5 },
                   { 8, 2, 5, 4 },
                   { 1, 8, 5, 9 } };
 
  // Function call to print the minimum
  // cost to reach bottom-right corner
  // from the top-left corner of the matrix
  minCost(grid, N);
 
  return 0;
}
 
// This code is contributed by Kingash.

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG
{
    static ArrayList<ArrayList<Character> > possibleWays;
 
    // Returns true if str[curr] does not matches with any
    // of the characters after str[start]
    static boolean shouldSwap(char str[], int start,
                              int curr)
    {
        for (int i = start; i < curr; i++)
        {
            if (str[i] == str[curr])
            {
                return false;
            }
        }
        return true;
    }
 
    // Prints all distinct permutations in str[0..n-1]
    static void findPermutations(char str[], int index,
                                 int n)
    {
        if (index >= n)
        {
            ArrayList<Character> l = new ArrayList<>();
            for (char ch : str)
                l.add(ch);
            possibleWays.add(l);
            return;
        }
 
        for (int i = index; i < n; i++) {
 
            // Proceed further for str[i] only if it
            // doesn't match with any of the characters
            // after str[index]
            boolean check = shouldSwap(str, index, i);
            if (check) {
                swap(str, index, i);
                findPermutations(str, index + 1, n);
                swap(str, index, i);
            }
        }
    }
 
    // Function for the swap
    static void swap(char[] str, int i, int j)
    {
        char c = str[i];
        str[i] = str[j];
        str[j] = c;
    }
 
    // Function to print the minimum cost
    static void minCost(int grid[][], int N)
    {
 
        ArrayList<Character> moveList = new ArrayList<>();
 
        // Making top-left value 0
        // implicitly to generate list of moves
        grid[0][0] = 0;
        ArrayList<Integer> possibleWaysSum
            = new ArrayList<>();
 
        for (int k = 0; k < N - 1; k++) {
 
            moveList.add('i');
            moveList.add('j');
 
            possibleWays = new ArrayList<>();
 
            // Convert into set to make only unique values
            int n = moveList.size();
            char str[] = new char[n];
            for (int i = 0; i < n; i++)
                str[i] = moveList.get(i);
 
            // To store the unique permutation of moveList
            // into the possibleWays
            findPermutations(str, 0, n);
            possibleWaysSum = new ArrayList<>();
 
            // Traverse the list
            for (ArrayList<Character> way : possibleWays) {
                int i = 0, j = 0, tempSum = 0;
                for (char move : way) {
                    if (move == 'i') {
                        i += 1;
                    }
                    else {
                        j += 1;
                    }
                   
                    // Stores cost according to given
                    // conditions
                    tempSum = (int)(Math.floor(tempSum / 2))
                              + grid[i][j];
                }
                possibleWaysSum.add(tempSum);
            }
        }
 
        // Print the minimum possible cost
        int ans = possibleWaysSum.get(0);
        for (int i = 1; i < possibleWaysSum.size(); i++)
            ans = Math.min(ans, possibleWaysSum.get(i));
 
        System.out.println(ans);
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Size of the grid
        int N = 4;
 
        // Given grid[][]
        int grid[][] = { { 0, 3, 9, 6 },
                         { 1, 4, 4, 5 },
                         { 8, 2, 5, 4 },
                         { 1, 8, 5, 9 } };
 
        // Function call to print the minimum
        // cost to reach bottom-right corner
        // from the top-left corner of the matrix
        minCost(grid, N);
    }
}
 
// This code is contributed by Kingash.

Python3

# Python3 program for the above approach
 
from itertools import permutations
from math import floor
 
# Function to print the minimum cost
 
 
def minCost(grid, N):
    moveList = []
 
    # Making top-left value 0
    # implicitly to generate list of moves
    grid[0][0] = 0
 
    for i in range(N - 1):
        moveList.append('i')
        moveList.append('j')
 
        # Convert into set to make only unique values
        possibleWays = list(set(permutations(moveList)))
        possibleWaysSum = []
 
        # Traverse the list
        for way in possibleWays:
            i, j, tempSum = 0, 0, 0
            for move in way:
                if move == 'i':
                    i += 1
                else:
                    j += 1
 
                # Stores cost according to given conditions
                tempSum = floor(tempSum/2) + grid[i][j]
 
            possibleWaysSum.append(tempSum)
        minWayIndex = possibleWaysSum.index(min(possibleWaysSum))
 
    # Print the minimum possible cost
    print(min(possibleWaysSum))
 
 
# Size of the grid
N = 4
 
# Given grid[][]
grid = [[0, 3, 9, 6], [1, 4, 4, 5], [8, 2, 5, 4], [1, 8, 5, 9]]
 
# Function call to print the minimum
# cost to reach bottom-right corner
# from the top-left corner of the matrix
minCost(grid, N)

Javascript

<script>
// Javascript program for the above approach
let possibleWays = [];
 
// Returns true if str[curr] does not matches with any
// of the characters after str[start]
function shouldSwap(str, start, curr) {
    for (let i = start; i < curr; i++) {
        if (str[i] == str[curr]) {
            return false;
        }
    }
    return true;
}
 
// Prints all distinct permutations in str[0..n-1]
function findPermutations(str, index, n) {
    if (index >= n) {
        let l = new Array();
        for (let ch of str)
            l.push(ch);
        possibleWays.push(l);
        return;
    }
 
    for (let i = index; i < n; i++) {
 
        // Proceed further for str[i] only if it
        // doesn't match with any of the characters
        // after str[index]
        let check = shouldSwap(str, index, i);
        if (check) {
            swap(str, index, i);
            findPermutations(str, index + 1, n);
            swap(str, index, i);
        }
    }
}
 
// Function for the swap
function swap(str, i, j) {
    let c = str[i];
    str[i] = str[j];
    str[j] = c;
}
 
// Function to print the minimum cost
function minCost(grid, N) {
 
    let moveList = new Array();
 
    // Making top-left value 0
    // implicitly to generate list of moves
    grid[0][0] = 0;
    let possibleWaysSum = new Array();
 
    for (let k = 0; k < N - 1; k++) {
 
        moveList.push('i');
        moveList.push('j');
 
        possibleWays = new Array();
 
        // Convert into set to make only unique values
        let n = moveList.length;
        let str = [];
        for (let i = 0; i < n; i++)
            str[i] = moveList[i];
 
        // To store the unique permutation of moveList
        // into the possibleWays
        findPermutations(str, 0, n);
        possibleWaysSum = new Array();
 
        // Traverse the list
        for (let way of possibleWays) {
            let i = 0, j = 0, tempSum = 0;
            for (let move of way) {
                if (move == 'i') {
                    i += 1;
                }
                else {
                    j += 1;
                }
 
                // Stores cost according to given
                // conditions
                tempSum = (Math.floor(tempSum / 2))
                    + grid[i][j];
            }
            possibleWaysSum.push(tempSum);
        }
    }
 
    // Print the minimum possible cost
    let ans = possibleWaysSum[0];
    for (let i = 1; i < possibleWaysSum.length; i++)
        ans = Math.min(ans, possibleWaysSum[i]);
 
    document.write(ans);
}
 
// Driver code
 
// Size of the grid
let N = 4;
 
// Given grid[][]
let grid = [[0, 3, 9, 6],
[1, 4, 4, 5],
[8, 2, 5, 4],
[1, 8, 5, 9]];
 
// Function call to print the minimum
// cost to reach bottom-right corner
// from the top-left corner of the matrix
minCost(grid, N);
 
// This code is contributed by Saurabh Jaiswal
</script>
Producción: 

12

 

Tiempo Complejidad: O(N 2 )
Espacio Auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por kashishmishra9911 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 *