// C# code to implement the approach
using System;
class GFG {
// Function to check the validity of the
// cell index so that it won't go outside
// of the grid
static bool is_valid(int x, int y, int[,] grid)
{
if (x < 0 || y < 0 || x >= grid.GetLength(0)
|| y >= grid.GetLength(1)) {
return false;
}
return true;
}
// Recursive function to check if there
// exist a path from the top leftmost
// corner to right bottommost corner x and
// y are coordinates of current cell
static void dfs(int x, int y, bool[,] visited,
int[,] grid)
{
if (visited[x,y]) {
return;
}
visited[x,y] = true;
int up = 0, down = 0, left = 0, right = 0;
if (grid[x,y] == 1) {
left = 1;
right = 1;
}
else if (grid[x,y] == 2) {
up = 1;
down = 1;
}
else if (grid[x,y] == 3) {
left = 1;
down = 1;
}
else if (grid[x,y] == 4) {
down = 1;
right = 1;
}
else if (grid[x,y] == 5) {
up = 1;
left = 1;
}
else {
right = 1;
up = 1;
}
if (up != 0) {
int new_x = x - 1, new_y = y;
if (is_valid(new_x, new_y, grid)
&& (grid[new_x,new_y] == 2
|| grid[new_x,new_y] == 3
|| grid[new_x,new_y] == 4)) {
dfs(new_x, new_y, visited, grid);
}
}
if (down != 0) {
int new_x = x + 1, new_y = y;
if (is_valid(new_x, new_y, grid)
&& (grid[new_x,new_y] == 2
|| grid[new_x,new_y] == 5
|| grid[new_x,new_y] == 6)) {
dfs(new_x, new_y, visited, grid);
}
}
if (left != 0) {
int new_x = x, new_y = y - 1;
if (is_valid(new_x, new_y, grid)
&& (grid[new_x,new_y] == 1
|| grid[new_x,new_y] == 4
|| grid[new_x,new_y] == 6)) {
dfs(new_x, new_y, visited, grid);
}
}
if (right != 0) {
int new_x = x, new_y = y + 1;
if (is_valid(new_x, new_y, grid)
&& (grid[new_x,new_y] == 1
|| grid[new_x,new_y] == 3
|| grid[new_x,new_y] == 5)) {
dfs(new_x, new_y, visited, grid);
}
}
}
public static void Main()
{
int[,] grid = { { 2, 4, 3 }, { 6, 5, 2 } };
int N = grid.GetLength(0);
int M = grid.GetLength(1);
bool[,] visited = new bool[N,M];
// Function call
dfs(0, 0, visited, grid);
if (visited[N - 1,M - 1]) {
Console.WriteLine("Possible");
}
else {
Console.WriteLine("Impossible");
}
}
}
// This code is contributed by Pushpesh Raj.