Click here to Skip to main content
6,595,444 members and growing! (21,660 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » Game Development » Games     Intermediate License: The Code Project Open License (CPOL)

Simple LINQ Sudoku Solver

By Mickael Magniez

A simple way to resolve a Sudoku grid, in 10 lines of code.
C# 3.0, .NET, LINQ, Dev
Version:2 (See All)
Posted:5 Sep 2008
Views:10,943
Bookmarked:28 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
25 votes for this article.
Popularity: 6.41 Rating: 4.58 out of 5

1
2 votes, 8.0%
2
1 vote, 4.0%
3
3 votes, 12.0%
4
19 votes, 76.0%
5

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.

sudoku.png

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;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mickael Magniez


Member

Occupation: Software Developer (Junior)
Location: France France

Other popular Game Development articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralBrute force solution Pinmemberbearskin15:09 8 Sep '08  
GeneralSimplification Pinmemberbearskin14:49 8 Sep '08  
GeneralAwesome Pinmembermerlin9817:07 5 Sep '08  
GeneralCool! PinmemberRob Philpott2:49 5 Sep '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 5 Sep 2008
Editor: Smitha Vijayan
Copyright 2008 by Mickael Magniez
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project