// C# program for the above approach
using System;
class GFG{
// Function to check if it is valid
// to move to the given index or not
static bool isValid(int[,] board, int i,
int j, int K)
{
if (board[i, j] <= K)
{
return true;
}
// Otherwise return false
return false;
}
// Function to check if there exists a
// path from the cell (X, Y) of the
// matrix to any boundary cell with
// sum of elements at most K or not
static bool findPath(int[,] board, int X, int Y,
int M, int N, int K)
{
// Base Case
if (X < 0 || X == M ||
Y < 0 || Y == N)
{
return true;
}
// If K >= board[X][Y]
if (isValid(board, X, Y, K))
{
// Stores the current element
int board_XY = board[X, Y];
// Mark the current cell as visited
board[X, Y] = int.MaxValue;
// Visit all the adjacent cells
if (findPath(board, X + 1, Y, M, N,
K - board_XY) ||
findPath(board, X - 1, Y, M, N,
K - board_XY) ||
findPath(board, X, Y + 1, M, N,
K - board_XY) ||
findPath(board, X, Y - 1, M, N,
K - board_XY))
{
return true;
}
// Mark the cell unvisited
board[X, Y] = board_XY;
}
// Return false
return false;
}
// Driver Code
public static void Main(string[] args)
{
int[,] grid = { { 25, 5, 25, 25, 25, 25 },
{ 25, 1, 1, 5, 12, 25 },
{ 25, 1, 12, 0, 15, 25 },
{ 22, 1, 11, 2, 19, 15 },
{ 25, 2, 2, 1, 12, 15 },
{ 25, 9, 10, 1, 11, 25 },
{ 25, 25, 25, 25, 25, 25 } };
int K = 17;
int M = grid.Length;
int N = grid.GetLength(0);
int X = 2, Y = 3;
if (findPath(grid, X, Y, M, N, K))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by AnkThon