Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Minimum Cost to cross Grid
MEDIUM
30 mins
4 upvotes
Graph
Dynamic Programming
Greedy
Matrices (2D Arrays)
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Matrices (2D Arrays)
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Minimum Cost to cross Grid

Contributed by
Yash_5830
Medium
yellow-spark
0/80
Avg time to solve 30 mins
Success Rate 70 %
Share
4 upvotes

Problem Statement

You are given a 2 - D grid having ‘N’ rows and ‘M’ columns. Each cell of the grid has an integer value written on it which denotes the cost it takes to pass through that cell. You are currently present at the Top-Left cell (0,0) and you want to reach the Bottom-Right cell (N - 1, M - 1). To do so, you start moving from the Top-Left cell and move through any of the adjacent cells until you reach the Bottom-Right cell. The total cost of the path will be the sum of the costs of all the cells that you have passed through in the path.

Given the cost of each cell in a 2 - D matrix 'MAT', your task is to find the minimum total cost that you need to spend to reach the Bottom-Right cell if you are starting from the Top-Left cell.

Note:
1) From any cell you can move UP, DOWN, LEFT, or RIGHT.

2) You cannot move out of the grid.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1 :
2
3 3
1 1 1
2 2 2
3 3 3
2 2
1 3
3 4
Sample output 1 :
8
8
Explanation of Sample output 1 :
For the first test case, the path (0,0) => (0,1) => (0,2) => (1,2) => (2,2) has the minimum total cost, i.e, 8. Hence, the answer is 8 in this case.

For the second test case, the path (0,0) => (0,1) => (1,1)  has the minimum total cost, i.e, 8. Hence, the answer is 8 in this case.
Sample Input 2 :
2
2 5
1 5 2 1 1
1 1 1 7 2
1 4
5 3 7 1
Sample output 2 :
10
16
Reset Code
Full screen
Auto
copy-code
Console