Ask Sudoku

Ask Sudoku

Code

We are happy to give you the code used for solving Sudoku. It's written is Java and it'is quiet simple. You may start by the class call Solver and follow the path.

You can reuse the code and consider it as in lgpl.

Solver.java Grid.java SolvingGrid.java Cell.java CellDecision.java GridUtils.java


package com.asksudoku.logic;

import java.util.ArrayList;
import java.util.List;

public class Grid {
  
  private int[][] grid;
  private List<Cell> inputCells;
  
  public Grid(){
    grid = new int[9][9];
    inputCells = new ArrayList();
  }

  public Grid(int[][] grid) {
    this.grid = grid;
  }

  public int[][] getGrid() {
    return grid.clone();
  }
  
  public String getStringValue(int x, int y){
    int value = grid[x][y];
    if (value != 0) return ""+value;
    return "";
  }
  
  public void addInput(int x, int y, int value){
    grid[x][y] = value;
    addInputCell(new Cell(x,y));
  }
  
  public void addInputCell(Cell cell){
    inputCells.add(cell);
  }
  
  public boolean isInputCell(int x, int y){
    return inputCells.contains(new Cell(x,y));
  }
  
  public void copyInputCell(Grid grid){
    inputCells = grid.inputCells;
  }
  
  public String displayArray(){
    String result = "  ";
    for (int i = 0; i < 9; i++) {
      result += i + "  ";
    }
    result += "\n";
    result += "  _________________________\n";
    for (int y = 0; y < 9; y++) {
      result += y + "|";
      for (int x = 0; x < 9; x++) {
        if (grid[x][y] == 0){
          result += ".  ";
        } else {
          result += grid[x][y]+"  ";
        }
      }
      result += "\n";
    }
    return result;
  }
  
  public Object clone() {
    int [][] cloned =  new int[9][9];

    for (int i = 0; i < 9; i++) {
      for (int j = 0; j < 9; j++) {
        cloned[i][j] = grid[i][j];
      }
    }
    
    Grid result = new Grid(cloned);
    result.inputCells = inputCells;
    return result;
  }
  
  
}