// C# program for the above approach
using System;
using System.Collections.Generic;
public class Cell {
public int x, y, left_moves, right_moves;
}
public class GFG {
// Maximum size for the grid
const int MAX_N = 2010;
static int[, ] grid = new int[MAX_N, MAX_N];
static int n, m, L, R, startRow, startCol,
reachable_cells = 0;
// Marking visited cells
static bool[, ] visited = new bool[MAX_N, MAX_N];
// Using deque for 0-1 BFS
static LinkedList<Cell> dq = new LinkedList<Cell>();
// Function to add a cell to the deque based on the
// direction
static void Enqueue(int x, int y, int left_moves,
int right_moves, bool is_front)
{
if (x >= 0 && y >= 0 && x < n && y < m
&& grid[x, y] == 0 && !visited[x, y]
&& left_moves <= L && right_moves <= R) {
visited[x, y] = true;
if (is_front) {
dq.AddFirst(new Cell{
x = x, y = y, left_moves = left_moves,
right_moves = right_moves });
}
else {
dq.AddLast(new Cell{
x = x, y = y, left_moves = left_moves,
right_moves = right_moves });
}
}
}
// 0-1 BFS to find reachable cells
static void BFS()
{
dq.AddFirst(new Cell{
x = startRow, y = startCol, left_moves = 0,
right_moves = 0 }); // Starting cell
visited[startRow, startCol] = true;
while (dq.Count > 0) {
var current_cell = dq.First.Value;
dq.RemoveFirst();
reachable_cells++;
// Explore neighboring cells in all four
// directions Left
Enqueue(current_cell.x - 1, current_cell.y,
current_cell.left_moves,
current_cell.right_moves, true);
// Right
Enqueue(current_cell.x + 1, current_cell.y,
current_cell.left_moves,
current_cell.right_moves, true);
// Upwards
Enqueue(current_cell.x, current_cell.y - 1,
current_cell.left_moves + 1,
current_cell.right_moves, false);
// Downwards
Enqueue(current_cell.x, current_cell.y + 1,
current_cell.left_moves,
current_cell.right_moves + 1, false);
}
}
static void Main()
{
// Input grid size, starting position, and allowed
// moves
n = 4;
m = 5;
startRow = 2;
startCol = 1;
L = 1;
R = 2;
// Input the grid
int[, ] inputGrid = { { 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 0 },
{ 0, 0, 0, 1, 1 },
{ 1, 0, 0, 0, 0 } };
// 1-based indexing
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
grid[i, j] = inputGrid[i, j];
}
}
// Execute 0-1 breadth-first search
BFS();
// Output the number of reachable cells
Console.WriteLine(reachable_cells);
}
}
// This code is contributed by Susobhan Akhuli