DEV Community

Cover image for Day 48 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 48 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/number-of-ways-to-arrive-at-destination/1

Path With Minimum Effort
Difficulty: Medium Accuracy: 53.13%

You are given a 2D array mat[][], of size n*m. Your task is to find the minimum possible path cost from the top-left cell (0, 0) to the bottom-right cell (n-1, m-1) by moving up, down, left, or right between adjacent cells.
Note: The cost of a path is defined as the maximum absolute difference between the values of any two consecutive cells along that path.
Examples:
Input: mat[][] = [[7, 2, 6, 5],
[3, 1, 10, 8]]

Output: 4
Explanation: The route of [7, 3, 1, 2, 6, 5, 8] has a minimum value of maximum absolute difference between any two consecutive cells in the route, i.e., 4.

Input: mat[][] = [[2, 2, 2, 1],
[8, 1, 2, 7],
[2, 2, 2, 8],
[2, 1, 4, 7],
[2, 2, 2, 2]]

Output: 0
Explanation: The route of [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] has a minimum value of maximum absolute difference between any two consecutive cells in the route, i.e., 0.

Constraints:
1 ≀ n, m ≀ 100
0 ≀ mat[i][j] ≀ 106

Solution:
class Solution:
def minCostPath(self, mat):
import heapq
n, m = len(mat), len(mat[0])
dist = [[10**9]*m for _ in range(n)]
dist[0][0] = 0
pq = [(0,0,0)]

    while pq:
        d, x, y = heapq.heappop(pq)
        if (x,y) == (n-1,m-1): return d
        for dx, dy in [(1,0),(-1,0),(0,1),(0,-1)]:
            nx, ny = x+dx, y+dy
            if 0<=nx<n and 0<=ny<m:
                nd = max(d, abs(mat[nx][ny] - mat[x][y]))
                if nd < dist[nx][ny]:
                    dist[nx][ny] = nd
                    heapq.heappush(pq, (nd, nx, ny))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)