Given a two dimensional grid, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.
Note : It is assumed that negative cost cycles do not exist in input matrix.
This problem is extension of below problem.
In previous problem only going right and bottom was allowed but in this problem we are allowed to go bottom, up, right and left i.e. in all 4 direction.
A cost grid is given in below diagram, minimum cost to reach bottom right from top left is 327 (= 31 + 10 + 13 + 47 + 65 + 12 + 18 + 6 + 33 + 11 + 20 + 41 + 20) The chosen least cost path is shown in green.
It is not possible to solve this problem using dynamic programming similar to previous problem because here current state depends not only on right and bottom cells but also on left and upper cells. We solve this problem using dijkstra’s algorithm. Each cell of grid represents a vertex and neighbor cells adjacent vertices. We do not make an explicit graph from these cells instead we will use matrix as it is in our dijkstra’s algorithm.
In below code Dijkstra’ algorithm’s implementation using C++ STL is used. The code implemented below is changed to cope with matrix represented implicit graph. Please also see use of dx and dy arrays in below code, these arrays are taken for simplifying the process of visiting neighbor vertices of each cell.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Lexicographically largest prime path from top-left to bottom-right in a matrix
- Minimum cost to reach a point N from 0 with two different operations allowed
- Minimum odd cost path in a matrix
- Minimum cost for acquiring all coins with k extra coins allowed with every coin
- Print all possible paths from top left to bottom right of a mXn matrix
- Count all possible paths from top left to bottom right of a mXn matrix
- Print all palindromic paths from top left to bottom right in a matrix
- Minimum cost path from source node to destination node via an intermediate node
- Maximum points from top left of matrix to bottom right and return back
- Maximum sum path in a matrix from top to bottom
- Minimize Cost with Replacement with other allowed
- Min Cost Path | DP-6
- C Program for Min Cost Path
- Java Program for Min Cost Path
- Python Program for Min Cost Path