Skip to content

Commit 1deeb59

Browse files
committed
FindMinCostPath algorithm Added
1 parent 5784ffb commit 1deeb59

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import java.util.Comparator;
2+
import java.util.PriorityQueue;
3+
4+
class FindLowCostPath {
5+
6+
public static void main(String[] args) {
7+
int[][] maze = {
8+
{31, 100, 65, 12, 18},
9+
{10, 13, 47, 157, 6},
10+
{100, 113, 174, 11, 33},
11+
{88, 124, 41, 20, 140},
12+
{99, 32, 111, 41, 20}
13+
};
14+
15+
findShortCostPath(maze);
16+
}
17+
18+
private static void findShortCostPath(int[][] maze) {
19+
int X = maze.length, Y = maze[0].length;
20+
int[] mx = {-1, 0, 1, 0}, my = {0, 1, 0, -1};
21+
int[][] costPathArray = new int[X][Y];
22+
for (int i = 0; i < X; i++) {
23+
for (int j = 0; j < Y; j++) {
24+
costPathArray[i][j] = Integer.MAX_VALUE;
25+
}
26+
}
27+
28+
costPathArray[0][0] = maze[0][0];
29+
PriorityQueue<Cell> pq = new PriorityQueue<>(X * Y, Comparator.comparing(a -> a.distance));
30+
31+
Cell tempCell;
32+
pq.add(new Cell(0, 0, maze[0][0]));
33+
34+
while ((tempCell = pq.poll()) != null) {
35+
for (int i = 0; i < 4; i++) {
36+
int tempXMove = tempCell.x + mx[i];
37+
int tempYMove = tempCell.y + my[i];
38+
if (tempXMove > -1 && tempYMove > -1 && tempXMove < X && tempYMove < Y) {
39+
int tempMovedValue = maze[tempXMove][tempYMove];
40+
int updatedCurrentCell = costPathArray[tempCell.x][tempCell.y];
41+
int existCostCellValue = costPathArray[tempXMove][tempYMove];
42+
if (existCostCellValue > tempMovedValue + updatedCurrentCell) {
43+
if (costPathArray[tempXMove][tempYMove] != Integer.MAX_VALUE) {
44+
Cell existCell = new Cell(tempXMove, tempYMove, costPathArray[tempXMove][tempYMove]);
45+
pq.remove(existCell);
46+
}
47+
costPathArray[tempXMove][tempYMove] = tempMovedValue + updatedCurrentCell;
48+
pq.add(new Cell(tempXMove, tempYMove, costPathArray[tempXMove][tempYMove]));
49+
}
50+
}
51+
}
52+
}
53+
System.out.println(costPathArray[X - 1][Y - 1]);
54+
}
55+
56+
static class Cell {
57+
int x, y, distance;
58+
59+
public Cell(int x, int y, int distance) {
60+
this.x = x;
61+
this.y = y;
62+
this.distance = distance;
63+
}
64+
}
65+
}

0 commit comments

Comments
 (0)