using
System;
using
System.Collections.Generic;
class
GFG {
static
int
[] dx = { -1, 0, 1, 0 };
static
int
[] dy = { 0, 1, 0, -1 };
static
int
ROW = 5;
static
int
COL = 5;
class
Cell {
public
int
x;
public
int
y;
public
int
distance;
public
Cell(
int
x,
int
y,
int
distance)
{
this
.x = x;
this
.y = y;
this
.distance = distance;
}
}
class
DistanceComparer : IComparer<Cell> {
public
int
Compare(Cell a, Cell b)
{
if
(a.distance < b.distance) {
return
-1;
}
else
if
(a.distance > b.distance) {
return
1;
}
else
{
return
0;
}
}
}
static
bool
IsInsideGrid(
int
i,
int
j)
{
return
(i >= 0 && i < ROW && j >= 0 && j < COL);
}
static
int
ShortestPath(
int
[][] grid,
int
row,
int
col)
{
int
[][] dist =
new
int
[row][];
for
(
int
i = 0; i < row; i++) {
dist[i] =
new
int
[col];
for
(
int
j = 0; j < col; j++) {
dist[i][j] =
int
.MaxValue;
}
}
dist[0][0] = grid[0][0];
List<Cell> pq =
new
List<Cell>();
pq.Add(
new
Cell(0, 0, dist[0][0]));
pq.Sort(
new
DistanceComparer());
while
(pq.Count > 0) {
Cell curr = pq[0];
pq.RemoveAt(0);
for
(
int
i = 0; i < 4; i++) {
int
rows = curr.x + dx[i];
int
cols = curr.y + dy[i];
if
(IsInsideGrid(rows, cols)) {
if
(dist[rows][cols]
> dist[curr.x][curr.y]
+ grid[rows][cols]) {
if
(dist[rows][cols]
!=
int
.MaxValue) {
Cell adj =
new
Cell(
rows, cols,
dist[rows][cols]);
pq.Remove(adj);
}
dist[rows][cols]
= dist[curr.x][curr.y]
+ grid[rows][cols];
pq.Add(
new
Cell(rows, cols,
dist[rows][cols]));
pq.Sort(
new
DistanceComparer());
}
}
}
}
return
dist[row - 1][col - 1];
}
static
void
Main(
string
[] args)
{
int
[][] grid
= {
new
int
[] { 31, 100, 65, 12, 18 },
new
int
[] { 10, 13, 47, 157, 6 },
new
int
[] { 100, 113, 174, 11, 33 },
new
int
[] { 88, 124, 41, 20, 140 },
new
int
[] { 99, 32, 111, 41, 20 } };
Console.WriteLine(ShortestPath(grid, ROW, COL));
}
}