Skip to content
Snippets Groups Projects
Commit be4cb1b3 authored by tmp1u19's avatar tmp1u19 :octopus:
Browse files

Solver which solves mathdoku boards up until 5x5

parent d2689e86
No related branches found
No related tags found
No related merge requests found
import javafx.scene.layout.GridPane; 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 { public class Solver {
private int n; private int n;
private int[][] sol; private int[][] sol;
static int[][] solved;
private GridPane grid; private GridPane grid;
private boolean found = false;
public Solver(int n, GridPane grid) { public Solver(int n, GridPane grid) {
this.n = n; this.n = n;
sol = new int[n+1][n+1]; sol = new int[n+1][n+1];
solved = new int[n+1][n+1];
for(int i = 1; i <= n; i ++) { for(int i = 1; i <= n; i ++) {
for(int j = 1; j <= n; j ++) { for(int j = 1; j <= n; j ++) {
sol[i][j] = 0; sol[i][j] = 0;
} }
} }
this.grid = grid; this.grid = grid;
} }
...@@ -44,52 +52,50 @@ public class Solver { ...@@ -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; return true;
} }
boolean isSolution(int col, int row) { boolean isSolution(int col, int row) {
if(col == n && row == n) { if(col == n && row == n) {
Handler.getCell(grid, row - 1, col - 1).setValue(sol[row][col]);
return true; return true;
} }
return false; 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) { void backtracking(int row, int col) {
first(row, col); first(row, col);
while(next(row, col)) { while(next(row, col)) {
if(isValid(row, col)) { if(isValid(row, col)) {
if(isSolution(col, row) && Handler.verifyCages()) { if(isSolution(col, row)) {
out();
System.out.println(); 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 { } else {
if(col == n) { if(!found) {
backtracking(row + 1, 1); if(col == n) {
} else { backtracking(row + 1, 1);
backtracking(row, col + 1); } else {
backtracking(row, col + 1);
}
} }
} }
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment