The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."], ["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
 

注意:任意斜线也不能有两个Q

class Solution {
public List<List<String>> solveNQueens(int n) {
List<String> ans = new ArrayList<String>();
//initialize ans
for(int i = 0; i < n; i++){
StringBuilder s = new StringBuilder();
for(int j = 0; j < n; j++){
s.append(".");
}
ans.add(s.toString());
} dfs(n,0,ans);
return ret;
} public void dfs(int n, int depth, List<String> ans){ if(depth == n) {
List<String> new_ans = new ArrayList<String>(ans);
ret.add(new_ans);
return;
}
StringBuilder strBuilder = new StringBuilder(ans.get(depth));
for(int i = 0; i < n; i++){
if(check(n, ans, depth, i)) continue; //already have Q in this column strBuilder.setCharAt(i, 'Q');
ans.set(depth, strBuilder.toString());
dfs(n, depth+1, ans);
strBuilder.setCharAt(i, '.'); //recover
ans.set(depth, strBuilder.toString());
}
} public Boolean check(int n, List<String> ans, int i, int j){
for(int k = 0; k < i; k++){ //iterate n line
//i-k = j-x => x = j+k-i; i-k = x-j => x = i+j-k
if( ans.get(k).charAt(j) == 'Q'
||(j+k-i >= 0 && ans.get(k).charAt(j+k-i) == 'Q')
|| (i+j-k < n && ans.get(k).charAt(i+j-k) == 'Q'))
return true;
} return false;
} private List<List<String>> ret = new ArrayList<>();
}

最新文章

  1. SCNU ACM 2016新生赛初赛 解题报告
  2. 【结果很简单,过程很艰辛】记阿里云Ons消息队列服务.NET接口填坑过程
  3. JS判断用户手机是IOS还是Android
  4. ALV Tree demo(WBS元素分层显示)[引用别人的]
  5. Docker ntpdate Permition error
  6. MVC认知路【点点滴滴支离破碎】【四】----捆绑和缩小(BundleConfig.RegisterBundles)
  7. GATK-BWA-MEM handle GRCh38 alternate contig mappings
  8. 基于apt实现的Android快速持久化框架:AptPreferences
  9. LIS+LCS+LCIS
  10. Apache Spark源码走读之9 -- Spark源码编译
  11. phpstorm8注册码
  12. Andriod使用webview控件往APP里内嵌网页
  13. 编译LOADCEPC.EXE程序
  14. BZOJ 1618: [Usaco2008 Nov]Buying Hay 购买干草
  15. loj1341(数学)
  16. Dubbo源码学习--服务是如何引用的
  17. Java课程设计——猜数游戏(201521123111 陈伟泽)
  18. UVA - 11624 多点bfs [kuangbin带你飞]专题一
  19. &lt;a&gt;超链接用作下载
  20. DNS工作原理

热门文章

  1. java用Annotation注入到成员Bean对象
  2. n个数连接得到最小或最大的多位整数(携程)
  3. element UI 验证select 下拉问题
  4. mssql表分区
  5. Python 自动化
  6. 只含有一个Excel模板的工程发布问题
  7. 仿flash运动框架
  8. Aes加密/解密示例项目
  9. Linux增加虚拟内存方法
  10. HCL试验9