[C#] Sudoku Solver
Here’s some of the code I used back there to “hack” some coins at beliebtestewebseite.de.
It’s just the coded needed to solve (bruteforce) the sudokou.
*click*
Anyways. Hopefully you can use it. It’s written in C#.
The array “sudoku” contains all fields of the 9×9 sudoku.
A field contains “0″, if it’s “empty”.
If the exception “Solution found” is thrown/catched,the programm stops, because the solution is,obviously, found. *g*
There you go:
{ int[,] sudoku = new int[9, 9]; try { solve(0, 0); } catch (Exception ex) { MessageBox.Show("SCORE! :o"); } } } private void solve(int row, int col) { if( row > 8 ) throw new Exception( "Solution found" ) ; else { // Skip cells which are not empty while( sudoku[row,col] != 0 ) { if( ++col > 8 ) { col = 0 ; row++ ; // Throw an exception to stop the process if the puzzle is solved if (row > 8) throw new Exception( "Solution found" ) ; } } // Find a valid number for the empty cell for( int num = 1; num < 10; num++ ) { if( checkRow(row,num) && checkColumn(col,num) && checkBox(row,col,num) ) { sudoku[row,col] = num ; // Delegate work on the next cell to a recursive call if( col < 8 ) solve( row, col + 1 ) ; else solve( row + 1, 0 ) ; } } // No valid number was found, clean up and return to caller sudoku[row,col] = 0 ; } } private bool checkRow(int row, int num) { for (int col = 0; col < 9; col++) if (sudoku[row,col] == num) return false; return true; } private bool checkColumn(int col, int num) { for (int row = 0; row < 9; row++) if (sudoku[row, col] == num) return false; return true; } private bool checkBox(int row, int col, int num) { row = (row/3)*3; col = (col/3)*3; for (int r = 0; r < 3; r++) for (int c = 0; c < 3; c++) if (sudoku[row + r,col + c] == num) return false; return true; }
Recent Comments