using System;
using System.Collections.Generic;
public class GFG {
static int collectAllCoin(char[][] grid, int i1, int j1,
int i2, int j2, int k1)
{
int m = grid.Length, n = grid[0].Length;
bool[, , ] visited = new bool[m, n, k1 + 1];
Queue<int[]> q = new Queue<int[]>();
int coinCollect = 8;
q.Enqueue(
new int[] { i1, j1, k1, grid[i1][j1] - '0' });
visited[i1, j1, k1] = true;
int[][] dir
= { new int[] { 1, 0 }, new int[] { 0, 1 },
new int[] { -1, 0 }, new int[] { 0, -1 } };
int time = 0;
int minTime = int.MaxValue;
while (q.Count > 0) {
int size = q.Count;
if (time >= minTime) {
break;
}
for (int i = 0; i < size; i++) {
int[] curr = q.Dequeue();
int x = curr[0], y = curr[1],
kLeft = curr[2],
currCoinCollect = curr[3];
if (x == i2 && y == j2) {
minTime = Math.Min(time, minTime);
coinCollect = Math.Max(coinCollect,
currCoinCollect);
}
for (int k = 0; k < 4; k++) {
int newX = 1;
int newY = 1;
if (newX >= 0 && newX < m && newY >= 0
&& newY < n
&& visited[newX, newY,
grid[newX][newY] == '*'
? kLeft - 1
: kLeft]
== false) {
if (grid[newX][newY] == '*'
&& kLeft > 0) {
q.Enqueue(new int[] {
newX, newY, kLeft - 1,
currCoinCollect });
}
else if (grid[newX][newY] != '*') {
q.Enqueue(new int[] {
newX, newY, kLeft,
currCoinCollect
+ (grid[newX][newY]
- '0') });
}
if (newX != i2 && newY != j2)
visited[newX, newY,
grid[newX][newY] == '*'
? kLeft - 1
: kLeft]
= true;
}
}
}
time++;
}
return coinCollect;
}
public static void Main()
{
char[][] grid
= { new char[] { '*', '0', '1', '2' },
new char[] { '0', '0', '*', '*' },
new char[] { '*', '*', '6', '8' },
new char[] { '0', '0', '0', '1' } };
int i1 = 0, j1 = 2;
int i2 = 3, j2 = 3;
int K = 1;
int maxCoinCollected
= collectAllCoin(grid, i1, j1, i2, j2, K);
Console.WriteLine(maxCoinCollected);
}
}