51. N 皇后

算法记录

LeetCode 题目:

  n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。


思路

  • 算法记录
  • 说明
    • 一、题目
    • 二、分析
  • 总结


说明

一、题目

  给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。

二、分析

  • 求皇后问题最难的就是分清楚皇后不打架的情况.
  • 这个题还没有明确的给出棋盘的大小, 而且要返回的是字符串类型的一个两层列表, 都知道 java 中最难处理的就是 string 类型了, 这个题的难点其实在这里.
  • 对于行上的皇后我们以行往下展开就不用进行判断了, 其余三个方向上的皇后以数组进行标识, 这个两个斜线方向的关系需要再纸上自己进行画画, 不然不好理解.
class Solution {
     
    private int[] x = new int[9];
    private int[] y = new int[18];
    private int[] z = new int[18];
    public List<List<String>> solveNQueens(int n) {
     
        LinkedList<String> ans = new LinkedList();
        List<List<String>> ret = new ArrayList();
        String temp = "";
        for(int j = 0; j < n; j++) temp += ".";
        dfs(0, n, temp, ans, ret);
        return ret;
    }

    private void dfs(int ind, int n, String temp, LinkedList ans, List ret) {
     
        if(ind == n) {
     
            ret.add(new LinkedList(ans));
            return;
        }
        for(int i = 0; i < n; i++) {
     
            int ind1 = ind + i;
            int ind2 = n - i - 1 + ind;
            if(x[i] == 1 || y[ind1] == 1 || z[ind2] == 1) continue;
            StringBuilder builder = new StringBuilder(temp);
            builder.setCharAt(i, 'Q');
            ans.add(builder.toString());
            x[i] = y[ind1] = z[ind2] = 1;
            dfs(ind + 1, n, temp, ans, ret);
            x[i] = y[ind1] = z[ind2] = 0;
            ans.removeLast();
        }
    }
}

总结

熟悉字符串的处理和深度遍历。

你可能感兴趣的:(算法,leetcode,算法,皇后)