// C# code to implement the approach
using System;
using System.Collections.Generic;
public class GFG {
// Function to find all the coin from the
// grid in minimum number of time
static int collectAllCoin(char[][] grid, int i1, int j1,
int i2, int j2, int k1)
{
int m = grid.Length, n = grid[0].Length;
// For storing the i, j index is
// visited or not
bool[, , ] visited = new bool[m, n, k1 + 1];
// For BFS
Queue<int[]> q = new Queue<int[]>(); // <val, x, y>
// Final coin collect to reach
// destination in minimum time.
int coinCollect = 8;
// Pushing the current position
q.Enqueue(
new int[] { i1, j1, k1, grid[i1][j1] - '0' });
// Marking the current
// position visited
visited[i1, j1, k1] = true;
// Possible direction to move
int[][] dir
= { new int[] { 1, 0 }, new int[] { 0, 1 },
new int[] { -1, 0 }, new int[] { 0, -1 } };
// For counting the current
// time while moving
int time = 0;
// Storing the minimum time to
// reach at destination
int minTime = int.MaxValue;
while (q.Count > 0) {
int size = q.Count;
// This ensure that time has
// reached greater than minimum
// time to reach at destination
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);
}
// Explore all the direction
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) {
// Check if new cell is
// obstacle and any k
// move we have left to
// cross this obstacle
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;
}
}
}
// Incrementing the time taken
// after every level
time++;
}
// Return the total amount of time
// taken to collect all the coin
return coinCollect;
}
// Driver code
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;
// Function call
int maxCoinCollected
= collectAllCoin(grid, i1, j1, i2, j2, K);
Console.WriteLine(maxCoinCollected);
}
}