Skip to content

Instantly share code, notes, and snippets.

@drkpkg
Last active May 12, 2017 00:32
Show Gist options
  • Save drkpkg/c2efdc4efe927add1ea73db4e50597c2 to your computer and use it in GitHub Desktop.
Save drkpkg/c2efdc4efe927add1ea73db4e50597c2 to your computer and use it in GitHub Desktop.
Sudoku class
package sudoku;
import java.util.LinkedList;
public class Sudoku {
public void DoSudoku(int [][] board, int row, int column) {
if(isFinish(board)){showBoard(board); return;}
if(row >= board.length) return;
if(column >= board[row].length){
DoSudoku(board, row + 1, 0);
}
if(board[row][column] != 0){
DoSudoku(board, row, column + 1);
}
LinkedList<Integer> boardList = ListRules(board, row, column);
while(!boardList.isEmpty()){
board[row][column] = boardList.removeFirst();
DoSudoku(board, row, column + 1);
board[row][column] = 0;
}
}
private void showBoard(int[][] board) {
for (int row = 0; row < board.length; row++) {
for (int column = 0; column < board[row].length; column++) {
System.out.print(board[row][column] + " ");
}
System.out.println("");
}
}
private boolean isFinish(int[][] board) {
for (int row = 0; row < board.length; row++) {
for (int column = 0; column < board[row].length; column++) {
if(board[row][column] != 0){
return false;
}
}
}
return true;
}
public LinkedList<Integer> ListRules(int[][] board, int row, int column){
int value = 1;
LinkedList<Integer> list = new LinkedList<>();
while(value <= board.length){
if(inRow(board, row, value)
&& inColumn(board, column, value)
&& (inRegion(board, row, column, value))){
list.add(value);
}
value += 1;
}
return list;
}
private boolean inRegion(int[][] board, int row, int column, int value) {
int width = (int)Math.sqrt(board.length);
int rowSize = (row/width) * width;
int columnSize = (column/width) * width;
int auxSize = rowSize;
while(auxSize < auxSize + width){
int tempSize = columnSize;
while(tempSize < columnSize + width){
if(board[row][column] == value) return true;
tempSize += 1;
}
auxSize += 1;
}
return false;
}
private boolean inColumn(int[][] board, int position, int value) {
int actual = 0;
while(actual < board.length){
if(board[actual][position] == value){
return true;
}
actual += 1;
}
return false;
}
private boolean inRow(int[][] board, int position, int value) {
int actual = 0;
while(actual < board[position].length){
if(board[position][actual] == value) return true;
actual += 1;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment