using System.Collections.Generic;
private static readonly IEnumerable<int> defValues = Enumerable.Range(1, 9);
public static void Main()
var board = new int[9, 9]
public static void SolveSudoku(int[,] board)
Console.WriteLine("Input");
int rows = board.GetLength(0);
int cols = board.GetLength(1);
if (rows != 9 || cols != 9)
Console.WriteLine("Sudoku must be 9x9 in size");
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
found += FindCellValues(board, i, j, rows, cols);
Console.WriteLine("Output");
bool valid = Validate(board);
Console.WriteLine("Sudoku was solved: " + valid);
catch (SudokuException sex)
Console.WriteLine("There is an error when solving: " + sex.Message);
private static int FindCellValues(int[,] board, int i, int j, int rows, int cols)
int squareRow = (i / 3) * 3, squareCol = (j / 3) * 3;
List<int> deniedValues = new List<int>();
for (int j2 = 0; j2 < cols; j2++)
if (j2 != j && board[i, j2] > 0)
deniedValues.Add(board[i, j2]);
for (int i2 = 0; i2 < rows; i2++)
if (i2 != i && board[i2, j] > 0)
deniedValues.Add(board[i2, j]);
for (int i3 = squareRow; i3 < squareRow + 3; i3++)
for (int j3 = squareCol; j3 < squareCol + 3; j3++)
if (i3 != i && j3 != j && board[i3, j3] > 0)
deniedValues.Add(board[i3, j3]);
var res = defValues.Except(deniedValues).ToArray();
throw new SudokuException("Sudoku hasn't solution");
private static bool Validate(int[,] board)
for (int i = 0; i < board.GetLength(0); i++)
HashSet<int> row = new HashSet<int>();
for (int j = 0; j < board.GetLength(1); j++)
for (int j = 0; j < board.GetLength(1); j++)
HashSet<int> col = new HashSet<int>();
for (int i = 0; i < board.GetLength(0); i++)
for (int sqi = 0; sqi < board.GetLength(0) / 3; sqi++)
for (int sqj = 0; sqj < board.GetLength(1) / 3; sqj++)
HashSet<int> square = new HashSet<int>();
for (int i = sqi * 3; i < sqi * 3 + 3; i++)
for (int j = sqj * 3; j < sqj * 3 + 3; j++)
public static void WriteBoard(int[,] board)
StringBuilder sb = new StringBuilder();
sb.AppendLine("-------------------------------------");
for (int i=0; i < 9; i++)
for (int j=0; j < 9; j++)
sb.Append(board[i, j] + " | ");
sb.AppendLine("-------------------------------------");
Console.WriteLine(sb.ToString());
public class SudokuException : Exception
public SudokuException() : base()
public SudokuException(string message) : base(message)