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 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);
}
}
}
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment