using System;
public class Program {
static int N, M;
static int[] dx = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
static int[] dy = { 0, 0, 0, -1, -1, -1, 1, 1, 1 };
static bool IsValid(int x, int y)
{
return (x >= 0 && y >= 0 && x < N && y < M);
}
static void PrintGrid(bool[][] grid)
{
for (int row = 0; row < N; row++) {
for (int col = 0; col < M; col++) {
if (grid[row][col])
Console.Write("x ");
else
Console.Write("_ ");
}
Console.WriteLine();
}
}
static bool IsSafe(int[][] arr, int x, int y)
{
if (!IsValid(x, y))
return false;
for (int i = 0; i < 9; i++) {
if (IsValid(x + dx[i], y + dy[i])
&& (arr[x + dx[i]][y + dy[i]] - 1 < 0))
return false;
}
for (int i = 0; i < 9; i++) {
if (IsValid(x + dx[i], y + dy[i]))
arr[x + dx[i]][y + dy[i]]--;
}
return true;
}
static bool FindUnvisited(bool[][] visited,
int[] x, int[] y)
{
for (x[0] = 0; x[0] < N; x[0]++)
for (y[0] = 0; y[0] < M; y[0]++)
if (!visited[x[0]][y[0]])
return true;
return false;
}
static bool IsDone(int[][] arr, bool[][] visited)
{
bool done = true;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
done = done && (arr[i][j] == 0)
&& visited[i][j];
}
}
return done;
}
static bool SolveMinesweeper(bool[][] grid,int[][] arr,bool[][] visited)
{
bool done = IsDone(arr, visited);
if (done)
return true;
int[] x = { 0 };
int[] y = { 0 };
if (!FindUnvisited(visited, x, y))
return false;
visited[x[0]][y[0]] = true;
if (IsSafe(arr, x[0], y[0])) {
grid[x[0]][y[0]] = true;
if (SolveMinesweeper(grid, arr, visited))
return true;
grid[x[0]][y[0]] = false;
for (int i = 0; i < 9; i++) {
if (IsValid(x[0] + dx[i], y[0] + dy[i]))
arr[x[0] + dx[i]][y[0] + dy[i]]++;
}
}
if (SolveMinesweeper(grid, arr, visited))
return true;
visited[x[0]][y[0]] = false;
return false;
}
static void minesweeperOperations(int[][] arr,
int N, int M)
{
bool[][] visited = new bool[N][];
for (int i = 0; i < N; i++)
{
visited[i] = new bool[M];
}
bool[][] grid = new bool[N][];
for (int i = 0; i < N; i++)
{
grid[i] = new bool[M];
}
if (SolveMinesweeper(grid, arr, visited))
{
PrintGrid(grid);
}
else
{
Console.WriteLine("No solution exists");
}
}
static void Main(string[] args)
{
N = 7;
M = 7;
int[][] arr = { new int[] { 1, 1, 0, 0, 1, 1, 1 },
new int[] { 2, 3, 2, 1, 1, 2, 2 },
new int[] { 3, 5, 3, 2, 1, 2, 2 },
new int[] { 3, 6, 5, 3, 0, 2, 2 },
new int[] { 2, 4, 3, 2, 0, 1, 1 },
new int[] { 2, 3, 3, 2, 1, 2, 1 },
new int[] { 1, 1, 1, 1, 1, 1, 0 } };
minesweeperOperations(arr, N, M);
}
}