设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。
注意:本题相对原题做了扩展
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/eight-queens-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Scanner; class Solution { private List<List<String>> ans = new ArrayList<>(); private LinkedList<Integer> path = new LinkedList<>(); private void add() { List<String> item = new ArrayList<>(); for (int x : path) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < x; ++i) { sb.append("."); } sb.append("Q"); for (int i = x + 1; i < path.size(); ++i) { sb.append("."); } item.add(sb.toString()); } ans.add(item); } private int log2(int x) { return (int) (Math.log(x) / Math.log(2) + 0.5); } private void solve(int LIMIT, int rowLimit, int leftLimit, int rightLimit) { if (rowLimit == LIMIT) { add(); return; } int allow = LIMIT & (~(rowLimit | leftLimit | rightLimit)); while (allow > 0) { int lowbit = allow & (-allow); path.offerLast(log2(lowbit)); solve(LIMIT, rowLimit | lowbit, (leftLimit | lowbit) << 1, (rightLimit | lowbit) >> 1); allow -= lowbit; path.pollLast(); } } public List<List<String>> solveNQueens(int n) { solve((1 << n) - 1, 0, 0, 0); return ans; } }