diff --git a/Solver.java b/Solver.java index 20866ff37ca05ac6814d41b29fde31799ca5f914..2354af52d7c35e33f19cfdb4cb1051439d734ffe 100644 --- a/Solver.java +++ b/Solver.java @@ -1,21 +1,29 @@ import javafx.scene.layout.GridPane; -import javax.print.attribute.HashDocAttributeSet; - +/** + * this class generates the solution for a mathdoku game + * the backtracking method is used below, generating matrices that respect the + */ public class Solver { private int n; private int[][] sol; + static int[][] solved; private GridPane grid; + private boolean found = false; public Solver(int n, GridPane grid) { + this.n = n; sol = new int[n+1][n+1]; + solved = new int[n+1][n+1]; + for(int i = 1; i <= n; i ++) { for(int j = 1; j <= n; j ++) { sol[i][j] = 0; } } + this.grid = grid; } @@ -44,52 +52,50 @@ public class Solver { } } - for(int i = 1; i < col; i ++) { - Handler.getCell(grid, row - 1, i - 1).setValue(sol[row][i]); - } - - for(int i = 1; i < row; i ++) { - Handler.getCell(grid, i - 1, col - 1).setValue(sol[i][col]); - } - - for(Cage cage : Handler.cages) { - if(!Handler.verifyCage(cage)) { - return false; - } - } - return true; } boolean isSolution(int col, int row) { if(col == n && row == n) { - Handler.getCell(grid, row - 1, col - 1).setValue(sol[row][col]); return true; } return false; } - void out() { - for(int i = 1; i <= n; i ++) { - for(int j = 1; j <=n; j ++) { - System.out.print(sol[i][j] + " "); - } - System.out.println(); - } - } - void backtracking(int row, int col) { first(row, col); while(next(row, col)) { if(isValid(row, col)) { - if(isSolution(col, row) && Handler.verifyCages()) { - out(); - System.out.println(); + if(isSolution(col, row)) { + + if(!found) { + for(int i = 1; i <= n; i ++) { + for(int j = 1; j <= n; j ++) { + Handler.getCell(grid, i - 1, j - 1).setValue(sol[i][j]); + } + } + + if(Handler.verifyCages()) { + found = true; + + for(int i = 0; i < n; i ++) { + for(int j = 0; j < n; j ++) { + solved[i][j] = sol[i + 1][j + 1]; + } + } + + break; + } + + } + } else { - if(col == n) { - backtracking(row + 1, 1); - } else { - backtracking(row, col + 1); + if(!found) { + if(col == n) { + backtracking(row + 1, 1); + } else { + backtracking(row, col + 1); + } } } }