Monday, April 7, 2014

N-Queens II @LeetCode

Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
package leetcode.combinations;
import java.util.ArrayList;
/**
* Solution: I am lazy... use the same way as N-Queen I
* @author jeffwan
* @date Apr 7, 2014
*/
public class TotalNQueens {
public int totalNQueens(int n) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> cols = new ArrayList<Integer>();
search(result, cols, n);
System.out.println(result);
return result.size();
}
private void search(ArrayList<ArrayList<Integer>> result,
ArrayList<Integer> cols, int n) {
if (cols.size() == n) {
result.add(new ArrayList<Integer>(cols));
return;
}
for (int col = 0; col < n; col++) {
if (!isValid(cols, col)) {
continue;
}
cols.add(col);
search(result, cols, n);
cols.remove(cols.size() - 1);
}
}
private boolean isValid(ArrayList<Integer> cols, int col) {
int row = cols.size();
for (int i = 0; i < row; i++) {
if (col == cols.get(i)) {
return false;
}
if (i - cols.get(i) == row - col) {
return false;
}
if (i + cols.get(i) == row + col) {
return false;
}
}
return true;
}
}

No comments:

Post a Comment