Многопоточное решение задачи о ферзях
Для решения задачи о ферзях на больших размерах доски я использую многопоточность. Но видимо я что-то неправильно делаю, потому что для любого размера доски выводится 0.
public class QueenThread {
private int N;
private int total;
private Thread[] threads;
private final Object o = new Object();
public QueenThread(int N, int threads) {
this.N = N;
this.threads = new Thread[N];
}
public QueenThread(int N) {
this.N = N;
this.threads = new Thread[Runtime.getRuntime().availableProcessors()];
}
private class Worker implements Runnable {
private int from;
private int to;
private Worker(int from, int to) {
this.from = from;
this.to = to;
}
@Override
public void run() {
for (int i = 0; i < threads.length; i++) {
int[] board = new int[N + 1];
solve(from, to, board);
}
}
}
public int calcQueen() throws InterruptedException {
int threadsN = threads.length;
for (int i = 0; i < threadsN; i++) {
int from = i * N / threadsN + 1;
int to = (i + 1) * N / threadsN;
threads[i] = new Thread(new Worker(from, to));
threads[i].start();
}
return total;
}
private void subSolve(int column, int[] board) {
if (column > N) {
synchronized (o) {
total++;
}
}
for (int j = 2; j <= N; j++) {
if (canPut(j, column, board)) {
board[column] = j;
subSolve(column + 1, board);
}
}
}
private void solve(int start, int end, int[] board) {
for (int i = start; i <= end; i++) {
board[1] = i;
subSolve(2, board);
}
}
private boolean canPut(int row, int column, int[] board) {
for (int i = 1; i <= column; i++) {
if (row == board[i] || board[i] - row == column - i || board[i] - row == i - column) { return false; }
}
return true;
}
public static void main(String[] args) throws InterruptedException {
QueenThread a = new QueenThread(10);
System.out.println(a.calcQueen());
}
}
Источник: Stack Overflow на русском