Sudoku
A sudoku puzzle is a grid of nine by nine cells, that has been subdivided into nine subgrids of three by three cells.
The objective of sudoku is to enter a digit from 1 through 9 in each cell, in such a way that:
1. Each horizontal row contains each digit exactly once
2. Each vertical column contains each digit exactly once
3. Each subgrid contains each digit exactly once
Public Shared Sub PrintSudoku(puzzle As Integer(,))
Console.WriteLine("+-----+-----+-----+")
For i As Integer = 1 To 9
For j As Integer = 1 To 9
Console.Write("|{0}", puzzle(i - 1, j - 1))
Next
Console.WriteLine("|")
If i Mod 3 = 0 Then
Console.WriteLine("+-----+-----+-----+")
End If
Next
End Sub
Public Shared Function SolveSudoku(puzzle As Integer(,), row As Integer, col As Integer) As Boolean
If row < 9 AndAlso col < 9 Then
If puzzle(row, col) <> 0 Then
If (col + 1) < 9 Then
Return SolveSudoku(puzzle, row, col + 1)
ElseIf (row + 1) < 9 Then
Return SolveSudoku(puzzle, row + 1, 0)
Else
Return True
End If
Else
For i As Integer = 0 To 8
If IsAvailable(puzzle, row, col, i + 1) Then
puzzle(row, col) = i + 1
If (col + 1) < 9 Then
If SolveSudoku(puzzle, row, col + 1) Then
Return True
Else
puzzle(row, col) = 0
End If
ElseIf (row + 1) < 9 Then
If SolveSudoku(puzzle, row + 1, 0) Then
Return True
Else
puzzle(row, col) = 0
End If
Else
Return True
End If
End If
Next
End If
Return False
Else
Return True
End If
End Function
Private Shared Function IsAvailable(puzzle As Integer(,), row As Integer, col As Integer, num As Integer) As Boolean
Dim rowStart As Integer = (row \ 3) * 3
Dim colStart As Integer = (col \ 3) * 3
For i As Integer = 0 To 8
If puzzle(row, i) = num Then
Return False
End If
If puzzle(i, col) = num Then
Return False
End If
If puzzle(rowStart + (i Mod 3), colStart + (i \ 3)) = num Then
Return False
End If
Next
Return True
End Function
Example
Dim puzzle As Integer(,) = {
{3, 2, 1, 7, 0, 4, 0, 0, 0},
{6, 4, 0, 0, 9, 0, 0, 0, 7},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 4, 5, 9, 0, 0},
{0, 0, 5, 1, 8, 7, 4, 0, 0},
{0, 0, 4, 9, 6, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{2, 0, 0, 0, 7, 0, 0, 1, 9},
{0, 0, 0, 6, 0, 9, 5, 8, 2}
}
If SolveSudoku(puzzle, 0, 0) Then
PrintSudoku(puzzle)
End If
Output
+-----+-----+-----+
|3|2|1|7|5|4|6|9|8|
|6|4|8|2|9|3|1|5|7|
|5|7|9|8|1|6|2|3|4|
+-----+-----+-----+
|7|8|2|3|4|5|9|6|1|
|9|6|5|1|8|7|4|2|3|
|1|3|4|9|6|2|8|7|5|
+-----+-----+-----+
|8|9|3|5|2|1|7|4|6|
|2|5|6|4|7|8|3|1|9|
|4|1|7|6|3|9|5|8|2|
+-----+-----+-----+