编辑代码

import java.util.LinkedList;

public class Queue {
    private static boolean isCorrectColumn(int col, int curRow, int queueCount, int[] path) {
        boolean bCorrect = true;
        int leftup = col - 1;
        int rightup = col + 1;

        for (int i = curRow - 1; i >= 0; --i) {
            if (path[i] == col) {
                //在同一列
                bCorrect = false;
                break;
            }

            if (leftup >= 0 && path[i] == leftup) {
                //在同一左斜线上
                bCorrect = false;
                break;
            }

            if ( rightup < queueCount && path[i] == rightup) {
                //在同一右斜线上
                bCorrect = false;
                break;
            }
            --leftup;
            ++rightup;
        }

        return bCorrect;
    }
    public static void findQueuePos(int queueCount, int curRow, int[] path, LinkedList<int[]> solutions) {
        if (queueCount == curRow) {
            solutions.add((int[])path.clone());
            return;
        }

        for (int i = 0; i < queueCount; ++i) {
            if (isCorrectColumn(i, curRow, queueCount, path)) {
                path[curRow] = i;
                findQueuePos(queueCount, curRow + 1, path, solutions);
            }
        }
    }

    public static LinkedList<int[]> solveQueueProblem(int queueCount) {
        LinkedList<int[]> solutions = new LinkedList<int[]>();
        int[] path = new int[queueCount];

        findQueuePos(queueCount, 0,  path, solutions);
        return solutions;
    }

    public static void printQueueSolutions(int queueCount, LinkedList<int[]> solutions) {
        System.out.println("皇后问题有" + solutions.size() + "种解决方案:");
        for (int[] solution:solutions) {
            for (int i = 0; i < solution.length; ++i) {
                for (int j = 0; j < queueCount; ++j) {
                    if (j == solution[i]) {
                        System.out.print('O');
                    }
                    else {
                        System.out.print('X');
                    }
                }
                System.out.println();
            }

            System.out.println();
            System.out.println();
        }
    }

    public  static void main(String[] args) {
        LinkedList<int[]> solutions = solveQueueProblem(4);
        printQueueSolutions(4, solutions);
    }
}