// C# program for the above approach
using System;
class GFG{
// Function to check if current
// position is safe or not
public static bool issafe(char[,] v, int i,
int j, int n,
int m, char ch)
{
// Directions for adjacent cells
int[] rowN = { 1, -1, 0, 0 };
int[] colN = { 0, 0, 1, -1 };
for(int k = 0; k < 4; k++)
{
// Check if any adjacent cell is same
if (i + rowN[k] >= 0 && i + rowN[k] < n &&
j + colN[k] >= 0 && j + colN[k] < m &&
v[(i + rowN[k]), (j + colN[k])] == ch)
{
return false;
}
}
// Current index is valid
return true;
}
// Recursive function for backtracking
public static bool place(char[,] v,
int n, int m)
{
int i = 0, j = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
// Free cell
if (v[i, j] == 'F')
{
break;
}
}
if (j != m)
{
break;
}
}
// All positions covered
if (i == n && j == m)
{
return true;
}
// If position is valid for 1
if (issafe(v, i, j, n, m, '1'))
{
v[i, j] = '1';
if (place(v, n, m))
{
return true;
}
v[i, j] = 'F';
}
// If position is valid for 2
if (issafe(v, i, j, n, m, '2'))
{
v[i, j] = '2';
// Recursive call for next
// unoccupied position
if (place(v, n, m))
{
return true;
}
// If above conditions fails
v[i, j] = 'F';
}
return false;
}
// Function to print valid matrix
public static void printMatrix(char[,] arr,
int n, int m)
{
place(arr, n, m);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
Console.Write(arr[i, j]);
}
Console.WriteLine();
}
}
// Driver Code
public static void Main()
{
char[,] arr = { { 'F', 'F', 'F', 'F' },
{ 'F', 'O', 'F', 'F' },
{ 'F', 'F', 'O', 'F' },
{ 'F', 'F', 'F', 'F' },};
// Give dimensions
int n = 4, m = 4;
// Function call
printMatrix(arr, n, m);
}
}
// This code is contributed by susmitakundugoaldanga