using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Sudoku_Brain
{
#region Grid Diagram
// 0 1 2 3 4 5 6 7 8
// -----------------
// 0 | | | |
// 1 | 0 | 1 | 2 |
// 2 | | | |
// |-----------------|
// 3 | | | |
// 4 | 3 | 4 | 5 |
// 5 | | | |
// |-----------------|
// 6 | | | |
// 7 | 6 | 7 | 8 |
// 8 | | | |
// -----------------
#endregion
#region SudokuSolver Class
class SudokuSolver
{
#region Fields & Properties
private int _AssignedRows = 0;
private int[,] _Grid = new int[9, 9];
public int[,] GetResult
{
get { return _Grid; }
}
public bool Solved
{
get
{
foreach (int i in _Grid)
if (i == 0) return false;
return true;
}
}
private int _MaxTries = 10000;
public int MaxTries
{
get { return _MaxTries; }
set { _MaxTries = value; }
}
#endregion
#region Grid Assignment
public void AssignRow(string values)
{
if (_AssignedRows != 9)
{
for (int i = 0; i < 9; i++)
_Grid[_AssignedRows, i] = int.Parse(values.ToString());
_AssignedRows++;
}
else
{
MessageBox.Show("You can only assign 9 rows to the grid.", "Too many rows", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
#region Solve Puzzle
public bool TrySolve()
{
if (_AssignedRows < 9)
{
MessageBox.Show("You have not assigned all rows to the grid yet.", "Missing Row(s)", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
List<int> obj;
int runs = 0;
int count = 0;
while (!Solved)
{
for (int row = 0; row < 9; row++)
{
for (int col = 0; col < 9; col++)
{
if (_Grid[row, col] == 0)
{
obj = new List<int>(GetColumn(col)
.Union(GetRow(row))
.Union(GetTile(row, col)))
.Distinct().ToList();
obj.Remove(0);
if (obj.Count == 8 || runs > 10)
{
if (runs > 10) runs = 0;
int x = Enumerable.Range(1, 9).FirstOrDefault(i => !obj.Contains(i));
_Grid[row, col] = x;
}
}
}
}
runs++;
count++;
if (count > MaxTries) return false;
}
return true;
}
#endregion
#region Grid Regions
private int[] GetTile(int x, int y)
{
int[] tile = new int[9];
int tileIndex = (x / 3) + (y / 3 * 3);
int tileRow = tileIndex / 3 * 3;
int tileColumn = tileIndex % 3 * 3;
int pos = 0;
for (int c = tileColumn; c < tileColumn + 3; c++)
{
for (int r = tileRow; r < tileRow + 3; r++)
{
tile[pos++] = _Grid[c, r];
}
}
return tile;
}
private int[] GetRow(int rowIndex)
{
int[] row = new int[9];
for (int i = 0; i < 9; i++)
row = _Grid[rowIndex, i];
return row;
}
private int[] GetColumn(int colIndex)
{
int[] col = new int[9];
for (int i = 0; i < 9; i++)
col = _Grid[i, colIndex];
return col;
}
#endregion
}
#endregion
}