Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimize cost to travel from source to destination in a Matrix based on given row change and column change cost

  • Last Updated : 10 Jan, 2022

Given an M*N grid, and given an array startPos[], indicating that the starting position is the cell (startPos[0], startPos[1]) and the array homePos[] indicating its destination is at the cell’s (homePos[0], homePos[1]).

From any cell movement is allowed only in four directions: left, right, up, and down, and cannot go outside the boundary. There are given two 0-indexed integer arrays: rowCosts[] of length M and colCosts[] of length N which denotes the costs of movements.

If there is upward or downward movement into a cell with row r, the cost of the move is rowCosts[r].  Similarly, if movement is made towards left or right into an adjacent cell c, the move costs colCosts.

Return the minimum total cost to travel from source to destination.

Note: There is no negative cost associated with any movement.

Examples:

Input: M = 3, N = 4, startPos[] = {1, 0}, homePos[] = {2, 3}, rowCosts[] = {5, 4, 3}, colCosts[] = {8, 2, 6, 7}
Output: 18
Explanation: One ideal path is: 

  • It starts at (1, 0) and descends to (2, 0). This move costs rowCosts[2] = 3.
  • It goes straight to (2, 1). This move costs colCosts[1] = 2.
  • It goes straight to (2, 2). This move costs colCosts[2] = 6.
  • It goes straight to (2, 3). This move costs colCosts[3] = 7.
  • The total cost is 3 + 2 + 6 + 7 = 18.

The movement is shown in the picture below:

Input: M = 3, N = 4, startPos[] = {0, 0}, homePos[] = {0, 0}, rowCosts[] = {5, 4, 3}, colCosts[] = {8, 2, 6, 7}
Output: 0
Explanation: Starting position and destination both are same. So no movement cost.

 

Approach: The solution relies on the observation:

To reach destination with minimum cost only the rows lying in the range [startPos[0], homePos[0]] and columns lying in the range [startPos[1], homePos[1]] should be crossed. 
Reason: Crossing any other row or column will add extra cost as all the movements have positive cost and number of movements increases with extra row and column traversal.

 So, the cost of each row and column between home and start positions will be incurred exactly once. Calculate cost to move between homePos[0] and startPos[0] rows. and homePos[1] and startPos[1] columns. Follow the steps below to solve the problem:

  • Initialize the variables rmin, cmin as the minimum of starting and ending position.
  • Initialize the variables rmax, cmax as the maximum of starting and ending position.
  • Iterate over the range [rmin, rmax] using the variable i and perform the following tasks:
    • Add the value rowCosts[i] to the variable ans.
  • Iterate over the range [cmin, cmax] using the variable i and perform the following tasks:
    • Add the value colCosts[i] to the variable ans.
  • Subtract the values rowCosts[startPos[0]], colCosts[startPos[1]] from the variable ans.
  • After performing the above steps, print the value of ans as the answer.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum cost
int minPathCost(vector<int>& startPos,
                vector<int>& homePos,
                vector<int>& rowCosts,
                vector<int>& colCosts)
{
    int ans = 0;
    int rmin = min(startPos[0], homePos[0]);
    int rmax = max(startPos[0], homePos[0]);
    int cmin = min(startPos[1], homePos[1]);
    int cmax = max(startPos[1], homePos[1]);
 
    // Determine the cost of the rows
    // that cross the path.
    for (int i = rmin; i <= rmax; i++)
        ans += rowCosts[i];
 
    // Determine the cost of the cols
    // that cross the path.
    for (int i = cmin; i <= cmax; i++)
        ans += colCosts[i];
 
    // Starting coordinates need to be
    // excluded from the final result
    ans -= rowCosts[startPos[0]];
    ans -= colCosts[startPos[1]];
 
    return ans;
}
 
// Driver Code
int main()
{
    vector<int> startpos{ 1, 0 };
    vector<int> homepos{ 2, 3 };
    vector<int> roscost{ 5, 4, 3 };
    vector<int> colcst{ 8, 2, 6, 7 };
 
    cout << minPathCost(startpos, homepos,
                        roscost, colcst);
 
    return 0;
}

Java




// Java code to implement the above approach
import java.util.*;
public class GFG
{
   
  // Function to find the minimum cost
  static int minPathCost(int []startPos,
                         int []homePos,
                         int []rowCosts,
                         int []colCosts)
  {
    int ans = 0;
    int rmin = Math.min(startPos[0], homePos[0]);
    int rmax = Math.max(startPos[0], homePos[0]);
    int cmin = Math.min(startPos[1], homePos[1]);
    int cmax = Math.max(startPos[1], homePos[1]);
 
    // Determine the cost of the rows
    // that cross the path.
    for (int i = rmin; i <= rmax; i++)
      ans += rowCosts[i];
 
    // Determine the cost of the cols
    // that cross the path.
    for (int i = cmin; i <= cmax; i++)
      ans += colCosts[i];
 
    // Starting coordinates need to be
    // excluded from the final result
    ans -= rowCosts[startPos[0]];
    ans -= colCosts[startPos[1]];
 
    return ans;
  }
 
  // Driver code
  public static void main(String args[])
  {
    int []startpos = { 1, 0 };
    int []homepos = { 2, 3 };
    int []roscost = { 5, 4, 3 };
    int []colcst = { 8, 2, 6, 7 };
    System.out.println( minPathCost(startpos, homepos,
                                    roscost, colcst));
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Python3




# Python code to implement the above approach
 
# Function to find the minimum cost
def minPathCost(startPos, homePos, rowCosts, colCosts):
    ans = 0;
    rmin = min(startPos[0], homePos[0]);
    rmax = max(startPos[0], homePos[0]);
    cmin = min(startPos[1], homePos[1]);
    cmax = max(startPos[1], homePos[1]);
 
    # Determine the cost of the rows
    # that cross the path.
    for i in range(rmin,rmax+1):
        ans += rowCosts[i];
 
    # Determine the cost of the cols
    # that cross the path.
    for i in range(cmin, cmax + 1):
        ans += colCosts[i];
 
    # Starting coordinates need to be
    # excluded from the final result
    ans -= rowCosts[startPos[0]];
    ans -= colCosts[startPos[1]];
 
    return ans;
 
# Driver code
if __name__ == '__main__':
    startpos = [1, 0];
    homepos = [2, 3];
    roscost = [5, 4, 3];
    colcst = [8, 2, 6, 7];
    print(minPathCost(startpos, homepos, roscost, colcst));
 
# This code is contributed by 29AjayKumar

C#




// C# code to implement the above approach
using System;
 
public class GFG
{
   
  // Function to find the minimum cost
  static int minPathCost(int []startPos,
                         int []homePos,
                         int []rowCosts,
                         int []colCosts)
  {
    int ans = 0;
    int rmin = Math.Min(startPos[0], homePos[0]);
    int rmax = Math.Max(startPos[0], homePos[0]);
    int cmin = Math.Min(startPos[1], homePos[1]);
    int cmax = Math.Max(startPos[1], homePos[1]);
 
    // Determine the cost of the rows
    // that cross the path.
    for (int i = rmin; i <= rmax; i++)
      ans += rowCosts[i];
 
    // Determine the cost of the cols
    // that cross the path.
    for (int i = cmin; i <= cmax; i++)
      ans += colCosts[i];
 
    // Starting coordinates need to be
    // excluded from the readonly result
    ans -= rowCosts[startPos[0]];
    ans -= colCosts[startPos[1]];
 
    return ans;
  }
 
  // Driver code
  public static void Main(String []args)
  {
    int []startpos = { 1, 0 };
    int []homepos = { 2, 3 };
    int []roscost = { 5, 4, 3 };
    int []colcst = { 8, 2, 6, 7 };
    Console.WriteLine( minPathCost(startpos, homepos,
                                    roscost, colcst));
  }
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find the minimum cost
function minPathCost(startPos, homePos,
                     rowCosts, colCosts)
{
    let ans = 0;
    let rmin = Math.min(startPos[0], homePos[0]);
    let rmax = Math.max(startPos[0], homePos[0]);
    let cmin = Math.min(startPos[1], homePos[1]);
    let cmax = Math.max(startPos[1], homePos[1]);
 
    // Determine the cost of the rows
    // that cross the path.
    for(let i = rmin; i <= rmax; i++)
        ans += rowCosts[i];
 
    // Determine the cost of the cols
    // that cross the path.
    for(let i = cmin; i <= cmax; i++)
        ans += colCosts[i];
 
    // Starting coordinates need to be
    // excluded from the final result
    ans -= rowCosts[startPos[0]];
    ans -= colCosts[startPos[1]];
 
    return ans;
}
 
// Driver Code
let startpos = [ 1, 0 ];
let homepos = [ 2, 3 ];
let roscost = [ 5, 4, 3 ];
let colcst = [ 8, 2, 6, 7 ];
 
document.write(minPathCost(startpos, homepos,
                           roscost, colcst));
 
// This code is contributed by Potta Lokesh
 
</script>
Output
18

Time Complexity: O(M + N)
Auxiliary Space: O(1)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!