 GeeksforGeeks App
Open App Browser
Continue

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

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

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 = 3.
• It goes straight to (2, 1). This move costs colCosts = 2.
• It goes straight to (2, 2). This move costs colCosts = 6.
• It goes straight to (2, 3). This move costs colCosts = 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, homePos] and columns lying in the range [startPos, homePos] 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 and startPos rows. and homePos and startPos 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], colCosts[startPos] 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 ``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, homePos);``    ``int` `rmax = max(startPos, homePos);``    ``int` `cmin = min(startPos, homePos);``    ``int` `cmax = max(startPos, homePos);` `    ``// 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];``    ``ans -= colCosts[startPos];` `    ``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, homePos);``    ``int` `rmax = Math.Max(startPos, homePos);``    ``int` `cmin = Math.Min(startPos, homePos);``    ``int` `cmax = Math.Max(startPos, homePos);` `    ``// 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];``    ``ans -= colCosts[startPos];` `    ``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

 ``

Output

`18`

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

My Personal Notes arrow_drop_up