Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sudok;
- import javax.swing.*;
- public class Solver {
- private int[][] m = new int [9][9];
- //private JTextField[][]jt = SudokuSwing.getJt();
- public int getValue(int x,int y) {
- return m[x][y];
- }
- public void setValue(int x,int y,int z) {
- //if(x<0||x>8||z<1||z>9||y<0||y>8){
- //throw new IllegalArgumentException("Aja Baja");
- //}else
- m[x][y]=z;
- }
- public void loadJt() {
- for (int i=0;i<9;i++) {
- for (int j=0;j<9;j++) {
- try {
- setValue(i,j,SudokuSwing.getJt(i,j));
- }
- catch(Exception e){
- //setValue(i,j,0);
- }
- }
- }
- }
- public void clear(){
- for (int r=0;r<9;r++) {
- for (int c=0;c<9;c++) {
- m[r][c] = 0;
- }
- }
- }
- /** Logic check, adds the specified number val only if it fulfills all the requirements */
- public boolean tryAddNbr(int row, int col, int val) {
- if(row<0||row>8||val<1||val>9||col<0||col>8){
- return false;
- }else{
- return !(isInCol(col, val))&&!(isInRow(row, val))&&!(isInMatrix(row, col, val))&&!(hasNum(row,col))&&!(numOutOfBounds(val));
- }
- }
- public boolean isInCol(int col, int val){
- for( int i = 0; i<9; i++){
- if(getValue(i, col) == val){
- return true;
- }
- }
- return false;
- }
- public boolean isInRow(int row, int val){
- for(int i = 0; i<9; i++){
- if(getValue(row, i) == val){
- return true;
- }
- }
- return false;
- }
- public boolean hasNum(int row, int col){
- if(getValue(row, col)!=0){
- return true;
- }
- return false;
- }
- public boolean numOutOfBounds(int val){
- if( val > 9 || val < 1){
- return true;
- }
- return false;
- }
- public boolean isInMatrix(int row, int col, int val){
- int r = (row/3)*3;
- int c = (col/3)*3;
- for(int i =0; i<3; i++){
- for(int j = 0; j<3; j++){
- if(getValue(r+i, c+j) == val){
- return true;
- }
- }
- }
- return false;
- }
- /** Wrapper method for solve */
- public boolean solve() {
- return solve(0, 0);
- }
- private boolean solve(int row, int col){
- if(col == 9){
- col=0;
- row++;
- }
- if(row==9){
- return true;
- }
- for(int num = 1; num<10; num++){
- if(tryAddNbr(row,col,num)){
- setValue(row, col, num);
- if(solve(row, col+1)){
- return true;
- }
- }else{
- setValue(row, col, 0);
- }
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement