VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-cost-to-reach-the-end-of-the-matrix/

⇱ Minimum Cost to reach the end of the matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Cost to reach the end of the matrix

Last Updated : 23 Jul, 2025

Given a matrix of size N X N, such that each cell has an Uppercase Character in it, find the minimum cost to reach the cell (N-1, N-1) starting from (0, 0). From a cell (i, j), we can move Up(i-1, j), Down(i+1, j), Left (i, j-1) and Right(i, j+1). If the adjacent cell has the same character as the current cell then we can move to the adjacent cell with 0 cost, else the cost incurred is 1 coin.

Examples:

Input: m = 2, n = 3, mat = { { 'a', 'b', 'n' }, { 'd', 'e', 'f' } }
Output: 3
Explanation: One of the possible answers is to move from 'a' -> 'b' -> 'e' -> 'f' with the cost of 1 + 1 + 1 = 3

Input: m = 2, n = 2, mat = {{'a', 'a'}, {'a', 'a'}}
Output: 0
Explanation: We can take any path from the top left to the bottom right as the cost is always zero.

Approach: To solve the problem follow the below idea:

The idea is to use Breadth-First Search (BFS) to find the shortest path from the top-left corner to the bottom-right corner of a matrix. Determine the character in each cell, where moving to an adjacent cell with the same character incurs a 0 cost, and moving to a different character incurs a cost of 1 coin. The distance matrix is updated during BFS to keep track of the minimum cost to reach each cell. The code then initializes the matrix, performs BFS, and outputs the minimum cost to reach the destination.

Step-by-step approach:

  • Initialize a distance matrix (dis[][]) with large values (INF).
  • Start BFS from the top-left corner (cell (0, 0)).
    • Use a deque (dq) to store cells to be processed.
    • For each cell in the deque, explore its neighbors (up, down, left, right).
    • Update the distance matrix dis[][] based on the cost of moving to the neighbor (0 or 1 coin).
    • Push the neighbor to the front of the deque if the character of the neighbor is same as the current cell otherwise push it to the back of the deque.
  • Finally, return the answer as dis[m-1][n-1]

Below is the implementation of the above approach:


Output
Shortest Path Distance: 3

Time Complexity: O(m * n), where 'm' is the number of rows and 'n' is the number of columns in the matrix.
Auxiliary Space: O(m * n)

Comment
Article Tags: