13,090,178 members (49,572 online)
alternative version

Stats

35K views
38 bookmarked
Posted 4 Sep 2008

Simple LINQ Sudoku Solver

, 4 Sep 2008
 Rate this:
A simple way to resolve a Sudoku grid, in 10 lines of code.

Introduction

This is a simple solution to resolve a Sudoku Grid, using LINQ. You can download a WinForm example that uses this method from the above link.

It solves all grids I tested in less than 1 second.

Using the code

The solver takes a list of integers, and returns the solution in the same type.

```private List<int> solver(List<int> _cells)
{
var emptyCell = _cells.Select((val, index) =>
new { index, val }).FirstOrDefault(cell => cell.val == 0);
if (emptyCell == null)
return _cells;
List<int> grid = new List<int>(_cells);

foreach (int trying in Enumerable.Range(1, 9).Except(_cells.Where((val, index) =>
sameRowColBox(index,emptyCell.index)).Distinct()))
{
grid[emptyCell.index] = trying;
if ((_cells = solver(grid)) != null)
return _cells;
}
return null;
}```

Briefly, the function takes an empty cell, tries to fill it with a correct value, and recursively calls the solver with this new grid.

The recursion stops when a correctly filled grid is found, or when all possibilities have been explored:

```if (emptyCell == null)
return _cells;```

Choose the first empty cell in the current grid, and get its index, thanks to the `Enumerable.Select` method:

```var emptyCell = _cells.Select((val, index) =>
new { index, val }).FirstOrDefault(cell => cell.val == 0); ```

Take all the possible values for this cell:

```Enumerable.Range(1, 9).Except(_cells.Where((val, index) =>
sameRowColBox(index,emptyCell.index)).Distinct())```

This function tests if two indexes are 'in conflict": same row; column, or 3*3 box.

```private bool sameRowColBox(int i, int j){
return (i / 9 == j / 9) || (i % 9 == j % 9) || (((i % 9) /
3 + (i / 9) / 3 * 3) == ((j % 9) / 3 + (j / 9) / 3 * 3));
}```

And then, for each possible value, fills the empty cell and recalls the solver.

```grid[emptyCell.index] = trying;
if ((_cells = solver(grid)).Count > 0 )
return _cells;```

Share

 Software Developer (Junior) France
No Biography provided

You may also be interested in...

 First Prev Next
 My vote of 5 Anurag Gandhi13-Dec-11 20:05 Anurag Gandhi 13-Dec-11 20:05
 My vote of 5 thatraja18-Jan-11 5:00 thatraja 18-Jan-11 5:00
 Brute force solution bearskin8-Sep-08 14:09 bearskin 8-Sep-08 14:09
 Simplification bearskin8-Sep-08 13:49 bearskin 8-Sep-08 13:49
 Re: Simplification Philippe Mori21-Aug-14 16:08 Philippe Mori 21-Aug-14 16:08
 Awesome merlin9815-Sep-08 6:07 merlin981 5-Sep-08 6:07
 Cool! Rob Philpott5-Sep-08 1:49 Rob Philpott 5-Sep-08 1:49
 Last Visit: 31-Dec-99 18:00     Last Update: 19-Aug-17 5:38 Refresh 1