LintCode 33.N皇后问题

描述:

n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击。

给定一个整数n,返回所有不同的n皇后问题的解决方案。

每个解决方案包含一个明确的n皇后放置布局,其中“Q”和“.”分别表示一个女王和一个空位置。

样例:

例1:

输入:1
输出:
   [["Q"]]


例2:

输入:4
输出:
[
  // Solution 1
  [".Q..",
   "...Q",
   "Q...",
   "..Q."
  ],
  // Solution 2
  ["..Q.",
   "Q...",
   "...Q",
   ".Q.."
  ]
]

 

代码:

public class Solution {
    /*
     * @param n: The number of queens
     * @return: All distinct solutions
     */
    public List<List<String>> solveNQueens(int n) {
        // write your code here
        List<List<String>> result = new ArrayList<>();
        if (n <= 0) {
            return result;
        }
        List<Integer> cols = new ArrayList<>();
        dfsSearch(result, cols, n);
        return result;
    }

    public void dfsSearch(List<List<String>> result,List<Integer> cols, int n) {
        if (cols.size() == n) {
            result.add(drawChessboard(cols));
            return;
        }
        for (int colIndex = 0; colIndex < n; colIndex++) {
            //如果不可放置就跳过
            if (!isValid(cols, colIndex)) {
                continue;
            }
            cols.add(colIndex);
            dfsSearch(result, cols, n);
            cols.remove(cols.size() - 1);
        }
    }

    private List<String> drawChessboard(List<Integer> cols) {
        List<String> chessboard = new ArrayList<>();
        for (int row = 0; row < cols.size(); row++) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int col = 0; col < cols.size(); col++) {
                stringBuilder.append(cols.get(row) == col ? 'Q' : '.');
            }
            chessboard.add(stringBuilder.toString());
        }
        return chessboard;
    }

    private boolean isValid(List<Integer> cols, int column) {
        //这里把cols的坐标作为rowIndex,其中储存的值维colIndex
        //因为下一个存储在cols
        int row = cols.size();
        for (int rowIndex = 0; rowIndex < cols.size(); rowIndex++) {
            if (cols.get(rowIndex) == column) {
                return false;
            }
            if (cols.get(rowIndex) - column == rowIndex - row) {
                return false;
            }
            if (cols.get(rowIndex) - column == row - rowIndex) {
                return false;
            }
        }
        return true;
    }
}

补充说明:

后续添加

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值