n皇后问题Java求解

将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击即使其中任意两个皇后都不同列、同行和在一条斜线上
输入:n = 4
输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]


image
class Queen {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> solutions = new ArrayList<List<String>>();
        int[] array = new int[n]; //下标代表行,其值代表列
        Arrays.fill(array, -1); //初始化
        Set<Integer> columns = new HashSet<Integer>();
        Set<Integer> slope1s = new HashSet<Integer>();
        Set<Integer> slope2s = new HashSet<Integer>();
        backTrace(solutions, n, 0, columns, slope1s, slope2s, array);
        return solutions;
    }

    public void backTrace(List<List<String>> solutions, int n, int row, Set<Integer> columns, Set<Integer> slope1s, Set<Integer> slope2s, int[] array) {
        if (row == n) {
            //第一组解已排列好,生成棋盘
            List<String> board = generateBoard(array, n);
            solutions.add(board);
        } else {
            for (int i = 0; i < n; i++) {
                //以下几个if分别判断是否在同一列,同一右斜线,同一左斜线
                if (columns.contains(i))
                continue;
                int slope1= row - i;
                if (slope1s.contains(slope1))
                continue;
                int slope2= row + i;
                if (slope2s.contains(slope2))
                continue;
                array[row] = i;
                columns.add(i);
                slope1s.add(slope1);
                slope2s.add(slope2);
                backTrace(solutions, n, row + 1, columns, slope1s, slope2s, array);
                columns.remove(i);
                slope1s.remove(slope1);
                slope2s.remove(slope2);
            }
        }
    }

    public List<String> generateBoard(int[] array, int n) {
        List<String> board = new ArrayList<String>();
        for (int i = 0; i < n; i++) {
            char[] row = new char[n];
            Arrays.fill(row, '.');
            row[array[i]] = 'Q';
            board.add(new String(row));
        }
        return board;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 为啥叫N皇后问题,因为这是八皇后问题扩展至N的情况八皇后问题:如何能够在 8×8 的国际象棋棋盘上放置八个皇后,使...
    淳属虚构阅读 116评论 0 0
  • 题目描述 n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击(任意两个皇后不能位于同一行,同一列...
    CW不要无聊的风格阅读 174评论 0 0
  • 如果读者对于回溯算法思路解法还不是很了解,可以先点击链接查阅我之前的一篇博文《算法之【回溯算法】详解[https:...
    阿旭123阅读 2,033评论 0 1
  • 问题描述 n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击(不同行,不同列,不同对角线)。给定...
    Alfie20阅读 629评论 0 0
  • 转载请注明出处:https://www.jianshu.com/u/b03dcb8185b5[https://ww...
    Gyu2233阅读 284评论 0 0