static int[,] sudokuPuzzle = new int[9, 9]
{7, 8, 0, 4, 0, 0, 1, 2, 0},
{6, 0, 0, 0, 7, 5, 0, 0, 9},
{0, 0, 0, 6, 0, 1, 0, 7, 8},
{0, 0, 7, 0, 4, 0, 2, 6, 0},
{0, 0, 1, 0, 5, 0, 9, 3, 0},
{9, 0, 4, 0, 6, 0, 0, 0, 5},
{0, 7, 0, 3, 0, 0, 0, 1, 2},
{1, 2, 0, 0, 0, 7, 4, 0, 0},
{0, 4, 9, 2, 0, 6, 0, 0, 7}
public static void Main(string[] args)
if (SolveSudoku(sudokuPuzzle))
Console.WriteLine("No solution exists");
static bool SolveSudoku(int[,] grid)
if (!FindUnassignedLocation(grid, out row, out col))
for (int num = 1; num <= 9; num++)
if (IsSafe(grid, row, col, num))
static bool FindUnassignedLocation(int[,] grid, out int row, out int col)
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
static bool UsedInRow(int[,] grid, int row, int num)
for (int col = 0; col < 9; col++)
if (grid[row, col] == num)
static bool UsedInCol(int[,] grid, int col, int num)
for (int row = 0; row < 9; row++)
if (grid[row, col] == num)
static bool UsedInBox(int[,] grid, int boxStartRow,
int boxStartCol, int num)
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
if (grid[row + boxStartRow,
col + boxStartCol] == num)
static bool IsSafe(int[,] grid, int row,
return !UsedInRow(grid, row, num) &&
!UsedInCol(grid, col, num) &&
!UsedInBox(grid, row - row % 3 ,
static void PrintGrid(int[,] grid)
for (int row = 0; row < 9; row++)
for (int col = 0; col < 9; col++)
Console.Write(grid[row, col] + " ");