![]() |
VOOZH | about |
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 = 3Input: 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:
Below is the implementation of the above approach:
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)