The following code snippet will check whether placing a particular number at a particular position is valid or not.
board
is a 2d 9 x 9
array representing the sudoku game board.
An empty cell i.e. where you have not yet put any number would contain zero.
row
and col
are the rwo and column locations of the number num
you want to place
boolean isValidMove(int num, int row, int col)
{
//1. Check whether the horizontal run contains the number
for (int i = 0; i < 9; i++)
if (board[row][i] == num) return false;
//2. Check whether the vertical run contains the number
for (int i = 0; i < 9; i++)
if (board[i][col] == num) return false;
//3. Check whether the 3x3 grid contains the number
int starting_row = row / 3;
int starting_col = col / 3;
for (int i = starting_row * 3; i < starting_row * 3 + 3; i++)
for (int j = starting_col * 3; j < starting_col * 3 + 3; j++)
if (board[i][j] == num) return false;
return true;
}
What you can do is implement a recursive backtracking algorithm that tries all possible combinations for a cell (namely 1...9). If a number can be put in that cell proceed to the next one. If not discard the contents of the current cell and move back to the previous one to place the next valid number.