Adding all solutions of N Queen Problem to an arrayList - java

The n-queens puzzle is the problem of placing n queens on a (n×n) chessboard such that no two queens can attack each other.
I used backtracking to solve the problem. But I ran in a strange issue.
Below is the code I wrote:
import java.util.ArrayList;
public class NQueenProblem {
static ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
static ArrayList<ArrayList<Integer>> nQueen(int n) {
ArrayList<Integer> positions = new ArrayList<Integer>();
//boolean[][] placed = new boolean[n][n];
solveNQueenRec(n, 0, new boolean[n][n], positions);
//for dubugging purpose. This prints empty arrays. not able to understand why?
for (ArrayList<Integer> list : ans)
System.out.println(list);
return ans;
}
static void solveNQueenRec(int n, int col, boolean[][] placed, ArrayList<Integer> positions) {
if (col == n) {
//for debugging process
System.out.println("Adding " + positions);
ans.add(positions);
System.out.println("Added " + positions);
}
for (int row = 0; row < n && col < n; row++) {
if (isSafe(row, col, placed, n)) {
placed[row][col] = true;
positions.add(row + 1);
solveNQueenRec(n, col + 1, placed, positions);
placed[row][col] = false;
positions.remove(positions.size() - 1);
}
}
// return null;
}
private static boolean isSafe(int row, int col, boolean[][] placed, int n) {
boolean safe = true;
// checking if exists in same row
for (int i = 0; i < col; i++) {
if (placed[row][i])
safe = false;
}
// checking for upper diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (placed[i][j])
safe = false;
}
// checking for lower diagonal
for (int i = row, j = col; i < n && j >= 0; i++, j--) {
if (placed[i][j])
safe = false;
}
return safe;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
nQueen(4);
}
}
What I am not able to understand is why my ans is empty when I could see in logs list being added to my ans. Am I doing some silly mistake. Please help me with the issue. If possible please help me with links to understand the issue and how could I avoid these issues in future.

I think you believe that when the JVM executes
ans.add(positions);
that it is taking a copy of the current state of positions and adding it to the list. It isn't, it is doing exactly what the code says: adding a reference to an ArrayList to ans.
All the items in ans are references to the same ArrayList, and that array list is empty when you print out ans.

ans.add(positions);
is your "problem". You are just adding to ans a reference to the list positions. Thus ans is full of references to the same positions list. As you modify positions several time after insertion, until emptied it, at the end ans is full of n references (n being the number of solutions found) the same positions list that is empty at the end.
What you need is to insert a copy of the current positions list at the time a solution is found:
ans.add(new ArrayList<Integer>(positions));
copy is obtained by constructing a new list with the exact content of the original one.

Add this checking make sure it is greater than zero, then print out the answer. Moreover, add the print queen function, your will see the answer clearly. If this solve your problem, please make as answer.
for (ArrayList<Integer> list : ans) {
if (list.size() > 0)
System.out.println(list);
}
static void solveNQueenRec(int n, int col, boolean[][] placed, ArrayList<Integer> positions) {
if (col == n)
printQueens(positions);
for (int row = 0; row < n && col < n; row++) {
if (isSafe(row, col, placed, n)) {
placed[row][col] = true;
positions.add(row + 1);
solveNQueenRec(n, col + 1, placed, positions);
placed[row][col] = false;
positions.remove(positions.size() - 1);
}
}
// return null;
}
public static void printQueens(ArrayList<Integer> q) {
int n = q.size();
for (int i = 0; i < n; i++) {
for (int j = 1; j <= n; j++) {
if (q.get(i) == j)
System.out.print("Q ");
else
System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
solution to 4-queens sample:
* Q * *
* * * Q
Q * * *
* * Q *
* * Q *
Q * * *
* * * Q
* Q * *

Related

Iterative brute-force sudoku solver

I am trying to implement an iterative Sudoku solver. To avoid recursion I used a stack, but I'm having problems with its management. The starting board is represented by a String array (variable 'input' in the following code) in which each element is composed of 3 numbers: the [row, col] and its value (i.e, "006" means that the element in the 1st line and 1st col is 6) and is translated into an array of int by the constructor. When I run it, I cannot get a solution, so there are probably mistakes in the nested for cycles. Any help is 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 the board based on input array
for (int n = 0; n < input.length; ++n) {
int i = 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) {
for (int i = 0; i < 9; i++) {
for (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) {
for (int k = 0; k < 9; k++)
if (val == cells[k][j])
return false;
for (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);
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
if (current[row][col] == 0) {
for (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 by adding and removing the 0-th element of an ArrayList is a very bad idea: it forces the whole content of the array to be shifted back an forth every time. Use LinkedList or modify the end of the list.
When you add and remove the same instance of the matrix back and forth to the stack, it is still the same matrix object, even though you may call it "current" or any other name. This means that when you change something in the matrix and then remove it from your stack, the change stays there (and in every other element of your stack, which are identical links to the same object). The logic of your solution looks like it needs to store the previous state of the solution on the stack, if so - allocate a new array every time and copy the data (also not very efficient, but try starting there).
A good question has to be specific. "Why this doesn't work?" is a bad question. Fix the obvious problems first, debug, and if puzzled provide more information about the state of your program (data in, data on step #1...N, for example)

count islands of zeros in a matrix

I am trying to program following well-known counting islands problem.
and it is not giving me the expected output. Where am I going wrong?
My assumption is if 0's touch 0th row or column or dimension of matrix .. it will not be treated as island
Here is my code
public class Matrix {
static int rowCount = 5;
static int columnCount = 4;
static int[][] matrix = { {1,1,1,1,1},
{1,0,0,0,1},
{1,1,1,1,1},
{1,1,1,0,1}
};
static boolean[][] visited = new boolean[rowCount][columnCount];
private static int countIslands = 0;
public static void main(String[] args) {
try{
for(int i=0; i<rowCount; i++){
for(int j=0; j<columnCount; j++){
if(matrix[i][j]==0){
checkZeros(matrix, i, j);
System.out.println("returned " + i + j);
}
}
}
System.out.println(visited);
}catch(Exception e){
}
System.out.println(countIslands);
}
private static void checkZeros(int[][] matrix2, int i, int j) {
boolean valueWithinLimits = withinLimits(i,j);
System.out.println("checking for " + i + j);
if(valueWithinLimits) && checkAlreadyVisited(i,j)){
if(matrix[i][j+1]==0){
checkZeros(matrix2, i, j+1);
}
if(matrix[i+1][j+1]==0){
checkZeros(matrix2, i+1, j+1);
}
if(matrix[i+1][j]==0){
checkZeros(matrix2, i+1, j);
}
if(matrix[i+1][j-1]==0){
checkZeros(matrix2, i-1, j-1);
}
visited[i][j] = true;
System.out.println("i reached here when ij are : " + i + j);
countIslands ++;
}
}
private static boolean checkAlreadyVisited(int i, int j) {
System.out.println("visited found for " + i + j);
return visited[i][j-1] || visited[i-1][j-1] || visited[i-1][j] || visited[i-1][j+1];
}
private static boolean withinLimits(int i, int j) {
return (i>0 && i<rowCount-1 && j>0 && j<columnCount-1);
}
}
The below solution is tested and works perfectly fine for any possibility
package com.divyanshu.island;
/**
* <b>Assumption 1 : 1 is Land, 0 is water.</b>
* <b>Assumption 2 : It is all water outside the matrix.</b>
*
* Instantiate IslandCounter by passing a m*n matrix.
* Method getIslandCount gives you the count of island formed.
*
* </br></br>Or</br></br>
*
* Method getIslandCount gives the count of all connected 1s in a m*n matrix with values in 1 or 0.
*/
public class IslandCounter {
private Integer[][] matrix;
public IslandCounter(Integer[][] matrix) {
this.matrix = matrix;
}
public int getIslandCount() {
int count = 0;
if (matrix == null || matrix.length == 0) {
return count;
}
Integer[][] tempMatrix = matrix.clone();
for (int i = 0; i < tempMatrix.length; i++) {
for (int j = 0; j < tempMatrix[i].length; j++) {
if (detectIsland(tempMatrix, false, i, j, matrix.length - 1, matrix[i].length - 1)) {
count++;
}
}
}
return count;
}
private boolean detectIsland(Integer[][] tempMatrix,
boolean islandDetected,
int i,
int j,
int iMax,
int jMax) {
if (i > iMax || j > jMax || i < 0 || j < 0 || tempMatrix[i][j] == 0) {
return islandDetected;
} else {
tempMatrix[i][j] = 0;
islandDetected = true;
detectIsland(tempMatrix, islandDetected, i - 1, j, iMax, jMax);
detectIsland(tempMatrix, islandDetected, i, j - 1, iMax, jMax);
detectIsland(tempMatrix, islandDetected, i + 1, j, iMax, jMax);
detectIsland(tempMatrix, islandDetected, i, j + 1, iMax, jMax);
}
return islandDetected;
}
}
===================================================================================
/**
*
*/
package com.divyanshu.island;
import java.util.Random;
/**
*This is a Main-Class to test the IslandCounter.
*/
public class IslandTest {
/**
* #param args
*/
public static void main(String[] args) {
Integer[][] matrix = generateMatrix();
printMatrix(matrix);
IslandCounter counter = new IslandCounter(matrix);
System.out.println("Total islands in the matrix : " + counter.getIslandCount());
}
private static Integer[][] generateMatrix() {
Integer[][] matrix = new Integer[4][4];
Random random = new Random();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(2);
}
}
return matrix;
}
private static void printMatrix(Integer[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
What you can do to improve is to add an exclusion array: an array of elements that are zeros. For example, if you find a zero within limits, you can start looking around and see if there are any zeros. Keep looking until you find all of them. Then add every single one of these zeros to the exclusion array, and when you continue with the loop, make sure it skips the elements in the exclusion array. This is not code, but the outline of the logic of the program.
I think there are multiple problems in your code.
Your visited matrix is full of false, which mean that checkAlreadyVisited will always return false. Also, I don't understand why does this method checks surroundings to see if the current location is visited. Using a temporary matrix like visited is a good idea, but you should print both map to ensure that it works.
countIslands is never incremented because of the previous error, but once you'll have resolved it, it will be incremented on every call (which should match the number of 0 on your map). If you want his solution to work with the border constraint, you must apply his detectIsland on each border before the for loop.
Divyanshu's solution works, except that it counts 1 and doesn't consider that an island touching a border is not an island (as you said).
To correct your solution, the visited matrix must be a copy of the matrix before using it, checkAlreadyVisited should only scan [i][j] and not its surrondings, and you shouldn't increment countIslands at each call.
Again, print your maps at each turns and use an easier matric like:
static int[][] matrix = {{1,1,1},
{1,0,1},
{1,1,1},};
(Didn't saw this question was three monsth old... anyway, here you go)

Recursive method for Pascal's triangle

I have written a method to evaluate a Pascal's triangle of n rows. However when I test the method I receive the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
Here is the code:
public static int[] PascalTriangle(int n) {
int[] pt = new int[n + 1];
if (n == 0) {
pt[0] = 1;
return pt;
}
int[] ppt = PascalTriangle(n - 1);
pt[0] = pt[n] = 1;
for (int i = 0; i < ppt.length; i++) {
pt[i] = ppt[i - 1] + ppt[i];
}
return pt;
}
Please let me know if you have any ideas for how the code could be edited to fix the problem.
for(int i = 0; i < ppt.length; i++)
{
pt[i] = ppt[i-1] + ppt[i];
In your first iteration, i == 0 and so (i-1) == -1. This is the cause of the error.
You can special handle the boundaries to avoid this. Or as the others have suggested, start i at 1 instead of 0.
Here is some code a friend of mine came up with
import java.util.Scanner;
public class Pascal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows to print: ");
int rows = scanner.nextInt();
System.out.println("Pascal Triangle:");
print(rows);
scanner.close();
}
public static void print(int n) {
for (int i = 0; i < n; i++) {
for (int k = 0; k < n - i; k++) {
System.out.print(" "); // print space for triangle like structure
}
for (int j = 0; j <= i; j++) {
System.out.print(pascal(i, j) + " ");
}
System.out.println();
}
}
public static int pascal(int i, int j) {
if (j == 0 || j == i) {
return 1;
} else {
return pascal(i - 1, j - 1) + pascal(i - 1, j);
}
}
}
In this code:
pt[0] = pt[n] = 1;
for(int i = 0; i < ppt.length; i++)
{
pt[i] = ppt[i-1] + ppt[i];
}
the problem is that when i is 0, you're trying to access ppt[i-1] which is ppt[-1]. The thing to notice is that when i is 0, you don't need to execute the statement that sets pt[i], because you already set pt[0] up before the loop! Try initializing i to 1 instead of 0.
Improvement in #Clemson code using Dynamic Programming :
class Solution {
int[][] dp ;
public List<List<Integer>> generate(int numRows) {
dp = new int[numRows][numRows];
List<List<Integer>> results = new ArrayList<>();
pascal(results, numRows);
return results;
}
private void pascal(List<List<Integer>> results, int numRows) {
for(int i = 0; i < numRows; i++) {
List<Integer> list = new ArrayList<>();
for(int j = 0; j <= i ; j++) {
list.add(dfs(i, j));
}
results.add(list);
}
}
private int dfs(int i, int j) {
if(j == 0 || i == j) return 1;
if(dp[i][j] != 0) return dp[i][j];
return dp[i][j] = dfs(i - 1, j - 1) + dfs(i - 1, j );
}
}
This isn't the solution to your code but it is solution to printing Pascals Triangle using only recursion which means no loops, using the combinations formula. All it needs is a main method or demo class to create an instance of the PascalsTriangle class. Hope this helps future Java students.
public class PascalsTriangle {
private StringBuilder str; // StringBuilder to display triangle
/**
* Starts the process of printing the Pascals Triangle
* #param rows Number of rows to print
*/
public PascalsTriangle(int rows) {
str = new StringBuilder();
printTriangle(rows, str);
}
/**
* Uses recursion to function as an "outer loop" and calls
* itself once for each row in triangle. Then displays the result
* #param row The number of the row to generate
* #param str StringBuilder to insert each row into
*/
public static void printTriangle(int row, StringBuilder str) {
// calls itself until row equals -1
if (row >= 0) {
// calls lower function to generate row and inserts the result into front of StringBuilder
str.insert(0, getRow(row, 0) + "\n");
// calls itself with a decremented row number
printTriangle(row - 1, str);
} else {
// when the base case is reached - display the result
JOptionPane.showMessageDialog(null, str);
System.exit(0);
}
}
/**
* Uses recursion to act as the "inner loop" and calculate each number in the given row
* #param rowNumber Number of the row being generated
* #param elementNumber Number of the element within the row (always starts with 0)
* #return String containing full row of numbers or empty string when base case is reached
*/
public static String getRow(int rowNumber, int elementNumber) {
// calls itself until elementNumber is greater than rowNumber
if (elementNumber <= rowNumber) {
// calculates element using combinations formula: n!/r!(n-r)!
int element = fact(rowNumber) / (fact(elementNumber) * (fact(rowNumber - elementNumber)));
// calls itself for each element in row and returns full String
return element + " " + getRow(rowNumber, elementNumber + 1);
} else return "";
}
/**
* Helper function that uses recursion to calculate factorial of given integer
* #param n Number to calculate factorial
* #return Factorial
*/
public static int fact(int n) {
if (n <= 0)
return 1;
else
return n * fact(n - 1);
}

Issues with recursive backtracking

I am trying to implement a backtracking algorithm in Java, to solve a sudoku problem.
I'm 95% sure the problem is in solve method, but I included the two accesory methods in case.
Some of the strange-ish things I'm doing are just due to requirements/convenience, like the hard-coded initial values for the puzzle. I'm sure the issue lies near the bottom of my solve method, but I cannot figure it out...
My current problem is this: after working on the first row, and finding a potentially valid permutation of values, my program simply gives up. If I uncomment the line that prints "ROW IS DONE," it'll print that after ONE row, and no more output is given. Why is it giving up after the first row? Is there anything else about my implementation I should be worried about
EDIT: I made a lot of changes. It is getting very close. If I print when EXHAUST is true, I get a puzzle that has every row solved except the last one. It looks like it is undoing everything after it's solved/nearly solved it. I get the feeling that it might already reach point where the puzzle is fully solved, but I'm not passing back TRUE at the right time... What am I doing wrong now?
import java.util.ArrayList;
class Model
{
ArrayList<View> views = new ArrayList<View>();
int[][] grid =
{
{5,3,0,0,7,0,0,0,0},
{6,0,0,1,9,5,0,0,0},
{0,9,8,0,0,0,0,6,0},
{8,0,0,0,6,0,0,0,3},
{4,0,0,8,0,3,0,0,1},
{7,0,0,0,2,0,0,0,6},
{0,6,0,0,0,0,2,8,0},
{0,0,0,4,1,9,0,0,5},
{0,0,0,0,8,0,0,7,9}
};
/**
* Method solve
*
* Uses a backtracking algorithm to solve the puzzle.
*/
public boolean solve(int row, int col) //mutator
{
if(exhaust(row,col)) {printGrid(); return true;}
int rownext = row;
int colnext = col+1;
if(colnext>8)
{
colnext = 0;
rownext++;
}
if(grid[row][col] != 0) solve(rownext,colnext);
else //is == 0
{
for(int num = 1; num <= 9; num++)
{
if(!conflict(row,col,num)) //try a non-conflicting number
{
grid[row][col] = num;
if(solve(rownext,colnext)) return true;
grid[row][col] = 0;
}
}
}
return false;
}
/**
* Method exhaust
*
* Iteratively searches the rest of the puzzle for empty space
* using the parameters as the starting point.
*
* #return true if no 0's are found
* #return false if a 0 is found
*/
public boolean exhaust(int row, int col)
{
for(int i = row; i <= 8; i++)
{
for(int j = col; j <= 8; j++)
{
if(grid[i][j] == 0) return false;
}
}
System.out.printf("Exhausted.\n");
return true;
}
/**
* Method conflict
*
* Checks if the choice in question is valid by looking to see
* if the choice has already been made in the same row or col,
* or block.
*
* #return true if there IS a conflict
* #return false if there is NOT a conflict
*/
public boolean conflict(int row, int col, int num)
{
for(int j = 0; j <= 8; j++)
{
if(grid[row][j] == num) {
return true;
}
}
for(int i = 0; i <= 8; i++)
{
if(grid[i][col] == num) {
return true;
}
}
int rowstart = 0;
if(row>=3) rowstart = 3;
if(row>=6) rowstart = 6;
int colstart = 0;
if(col>=3) colstart = 3;
if(col>=6) colstart = 6;
for(int r = rowstart; r <= (rowstart + 2); r++)
{
for(int c = colstart; c <= (colstart + 2); c++)
{
if(grid[r][c] == num) {
return true;
}
}
}
return false;
}
}
Imagine you're moving forward smoothly, row by row, and haven't backtracked. Your next position is solve(1,1);. Pay attention to rownext as you trace through your code. You should see the problem quickly. If you aren't backtracking, rownext should hold its value of at least 1.

Sudoku Checker 2d array Java

So im having a bit of problem with my code.. It's suppose to cross check rows and columns for same integers.
this is what i have so far.. but when i run it, it only seems to check the first integer only. (for example the first line of the sudoku board reads. 1 2 2 2 2 2 2 2 2 2) it wont detect the obvious multiple 2's but if i change the input to 1 1 2 2 2 2 2 2 2 the error will come up of multiple 1's in this case. the multiple any suggestions to tweak my loops to make it go through the columns?
public static void validate(final int[][] sudokuBoard) {
int width = sudokuBoard[0].length;
int depth = sudokuBoard.length;
for (int i = 0; i < width; i++) {
int j = i;
int reference = sudokuBoard[i][j];
while (true) {
if ((j >= width) || (j >= depth)) {
break;
}
else if (i == j){
// do nothing
}
else if (j < width) {
int current = sudokuBoard[i][j];
if (current == reference) {
System.out.print("Invalid entry found (width)" + "\n");
System.out.print(current + "\n");
// invalid entry found do something
}
} else if (j < depth) {
// note reversed indexes
int current = sudokuBoard[j][i];
if (current == reference) {
System.out.print("Invalid entry found (depth)" + "\n");
System.out.print(current + "\n");
// invalid entry found do something
}
}
j++;
}
Your code is more complex than it should be. Why put everything in one single function when you could split in several different functions?
public static void Validate(final int[][] sudokuBoard)
{
int width = sudokuBoard[0].length;
int depth = sudokuBoard.length;
for(int i = 0; i < width; i++)
if(!IsValidRow(sudokuBoard, i, width))
{
//Do something - The row has repetitions
}
for(int j = 0; j < height; j++)
if(!IsValidColumn(sudokuBoard, j, width))
{
//Do something - The columns has repetitions
}
}
static bool IsValidRow(int[][] sudokuBoard, int referenceRow, int width)
{
//Compare each value in the row to each other
for(int i = 0; i < width; i++)
{
for(int j = i + 1; j < width; j++)
{
if(sudokuBoard[referenceRow][i] == sudokuBoard[referenceRow][j])
return false
}
}
return true;
}
static bool IsValidColumn(int[][] sudokuBoard, int referenceColumn, int height)
{
//Compare each value in the column to each other
for(int i = 0; i < height; i++)
{
for(int j = i + 1; j < height; j++)
{
if(sudokuBoard[i][referenceColumn] == sudokuBoard[j][referenceColumn])
return false
}
}
return true;
}
That way, your code is much more easily maintainable/readable. This code above hasn't been tested, but it should be about right.
I suggest debugging this code step by step to really understand what's going on, if that's not clear for you.
Given the constraints of sudoku (a row of n cells must contain the numbers 1-n only) you don't need an order n^2 search (per row or column), you can do it order n by keeping a bit array indicating which numbers you've seen. Here's the pseudo-code for checking rows, do the same for columns:
for i in 0 to depth-1 // rows
boolean seen[] = new seen[width];
for j in 0 to width-1 // columns
if seen[board[i][j]-1] == true
duplicate number
else
seen[board[i][j]-1] = true
I would break the functionality into smaller boolean checks. This way, you can validate row by row, column by column, and square by square. For instance
private boolean isValidRow(int[] row) {
// Code here to check for valid row (ie, check for duplicate numbers)
}
private boolean isValidColumn(int[] column) {
// Code here to check for valid column
}
private boolean isValidSquare(int[][] square) {
// Code here to check for valid square
}
Note that rows and columns only need to be passed a 1 dimensional array. Squares are a 2 dimensional array as you need to check a 3x3 area. You can also treat these methods as static as their functionality is independent of the Sudoku board instance.
Edit: A suggestion on row/column/square validation is to use a HashSet. Sets can only have 1 element of a certain value, so you can add elements and look for a failure. For example:
HashSet<Integer> hs = new HashSet<Integer>();
for(int i = 0; i < 9; i++) {
if(!hs.add(integerArray[i])) // HashSet.add returns 'false' if the add fails
// (ie, if the element exists)
return false;
}
return true;

Categories