Thursday, May 1, 2014

Solving Sudoku in Simpler Way

Here, I have presented simple logic to solve sudoku with simple methods.

public class MySudoku {
      public static void main(String[] args) {
            new MySudoku(new int[9][9]).display();
      }

      private final int[][] sudoku;

      public MySudoku(int[][] sudoku) {
            this.sudoku = sudoku;
            solve(0, 0);
      }

      public boolean checkColumn(int row, int value) {
            for (int column = 0; column < 9; column++) {
                  if (sudoku[row][column] == value) {
                        return false;
                  }
            }
            return true;
      }

      public boolean checkRow(int column, int value) {
            for (int row = 0; row < 9; row++) {
                  if (sudoku[row][column] == value) {
                        return false;
                  }
            }
            return true;
      }

      public boolean checkBox(int row, int column, int value) {
            int boxRow = (row / 3) * 3;
            int boxColumn = (column / 3) * 3;
            for (int aRow = 0; aRow < 3; aRow++) {
                  for (int aColumn = 0; aColumn < 3; aColumn++) {
                        if (sudoku[boxRow + aRow][boxColumn + aColumn] == value) {
                              return false;
                        }
                  }
            }
            return true;
      }

      public boolean solve(int row, int column) {
            if (row == 9) {
                  row = 0;
                  column = column + 1;
                  if (column == 9) {
                        return true;
                  }
            }

            if (sudoku[row][column] != 0) {
                  return solve(row + 1, column);
            }

            for (int value = 1; value <= 9; value++) {
                  if (checkBox(row, column, value)
                              && checkColumn(row, value)
                              && checkRow(column, value)) {
                        sudoku[row][column] = value;
                        if (solve(row + 1, column)) {
                              return true;
                        }
                  }
            }
            sudoku[row][column] = 0;
            return false;
      }

      public void display() {
            for (int row = 0; row < 9; row++) {
                  System.out.println();
                  for (int column = 0; column < 9; column++) {
                        System.out.print("\t" + String.valueOf(sudoku[row][column]));
                  }
                  System.out.println();
            }
      }

}

No comments:

Post a Comment