using System;
using System.Collections.Generic;
public class MainClass
{
public static int PossiblePath(int n, int m, int[][] grid)
{
if (grid[0][0] == 1 || grid[n - 1][m - 1] == 1)
{
return -1;
}
Queue<int[]> q = new Queue<int[]>();
q.Enqueue(new int[] { 0, 0 });
int[] dx = { -1, 0, 1, 0 };
int[] dy = { 0, 1, 0, -1 };
int[][] dis = new int[n][];
for (int i = 0; i < n; i++)
{
dis[i] = new int[m];
for (int j = 0; j < m; j++)
{
dis[i][j] = -1;
}
}
dis[0][0] = 0;
while (q.Count > 0)
{
int[] p = q.Dequeue();
int x = p[0];
int y = p[1];
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 0 && xx < n && yy >= 0 && yy < m && dis[xx][yy] == -1)
{
if (grid[xx][yy] == 0 || grid[xx][yy] == 2)
{
dis[xx][yy] = dis[x][y] + 1;
q.Enqueue(new int[] { xx, yy });
}
if (grid[xx][yy] == 2)
{
for (int j = 0; j < 4; j++)
{
int xxx = xx + dx[j];
int yyy = yy + dy[j];
if (xxx >= 0 && xxx < n && yyy >= 0 && yyy < m)
{
if (grid[xxx][yyy] == 1)
{
grid[xxx][yyy] = 0;
}
}
}
}
}
}
}
return dis[n - 1][m - 1];
}
public static void Main(string[] args)
{
int n = 3;
int m = 4;
int[][] grid = new int[][] {
new int[] { 0, 1, 2, 1 },
new int[] { 2, 1, 0, 0 },
new int[] { 0, 2, 1, 0 }
};
int result = PossiblePath(n, m, grid);
Console.WriteLine("Output: " + result);
}
}