java - Iterative brute-force sudoku solver -
i trying implement iterative sudoku solver. avoid recursion used stack, i'm having problems management. starting board represented string array (variable 'input' in following code) in each element composed of 3 numbers: [row, col] , value (i.e, "006" means element in 1st line , 1st col 6) , translated array of int constructor. when run it, cannot solution, there mistakes in nested cycles. appreciated.
import java.util.arraylist; public class sudokusolver { private int[][] matrix = new int[9][9]; private string[] input = { "006", "073", "102", "131", "149", "217", "235", "303", "345", "361", "378", "422", "465", "514", "521", "548", "582", "658", "679", "743", "752", "784", "818", "883" }; private arraylist<int[][]> stack = new arraylist<>(); public sudokusolver() { // building board based on input array (int n = 0; n < input.length; ++n) { int = integer.parseint(input[n].substring(0, 1)); int j = integer.parseint(input[n].substring(1, 2)); int val = integer.parseint(input[n].substring(2, 3)); matrix[i][j] = val; } stack.add(matrix); } private boolean issolution(int[][] cells) { (int = 0; < 9; i++) { (int j = 0; j < 9; j++) { if(cells[i][j] == 0) return false; } } return true; } private boolean isvalid(int i, int j, int val, int[][] cells) { (int k = 0; k < 9; k++) if (val == cells[k][j]) return false; (int k = 0; k < 9; k++) if (val == cells[i][k]) return false; return true; } private boolean iterativesudokusolver() { int[][] current = null; while(stack.size() > 0 && !issolution(stack.get(0))) { current = stack.remove(0); (int row = 0; row < 9; row++) { (int col = 0; col < 9; col++) { if (current[row][col] == 0) { (int val = 1; val <= 9; val++) { if (isvalid(row, col, val, current)) { current[row][col] = val; stack.add(0, current); break; } } } } } } if (current != null && issolution(current)) return true; else return false; } public static void main(string [] args) { sudokusolver sudokusolver = new sudokusolver(); boolean result = sudokusolver.iterativesudokusolver(); if (result) system.out.println("sudoku solved"); else system.out.println("sudoku not solved"); } }
- a stack implementation adding , removing 0-th element of arraylist bad idea: forces whole content of array shifted forth every time. use linkedlist or modify end of list.
- when add , remove same instance of matrix , forth stack, still same matrix object, though may call "current" or other name. means when change in matrix , remove stack, change stays there (and in every other element of stack, identical links same object). logic of solution looks needs store previous state of solution on stack, if - allocate new array every time , copy data (also not efficient, try starting there).
- a question has specific. "why doesn't work?" bad question. fix obvious problems first, debug, , if puzzled provide more information state of program (data in, data on step #1...n, example)
Comments
Post a Comment