CODE 82: N-Queens
来源:互联网 发布:网络专供款冰箱 编辑:程序博客网 时间:2024/06/08 05:00
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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."]]
public ArrayList<String[]> solveNQueens(int n) {// Note: The Solution object is instantiated only once and is reused by// each test case.ArrayList<Integer> cols = new ArrayList<Integer>();ArrayList<String[]> result = createNQueens(n, cols, 0);return result;}public ArrayList<String[]> createNQueens(int n, ArrayList<Integer> cols,int col) {// Note: The Solution object is instantiated only once and is reused by// each test case.ArrayList<String[]> results = new ArrayList<String[]>();for (int i = 0; i < n; i++) {if (cols.contains((Integer) i)) {continue;} else if (!cols.isEmpty()) {int j;for (j = cols.size() - 1; j >= 0; j--) {if (Math.abs(i - cols.get(j)) == cols.size() - j) {break;}}if (j >= 0) {continue;}}cols.add((Integer) i);StringBuilder sb = new StringBuilder();for (int j = 0; j < n; j++) {if (j != i) {sb.append('.');} else {sb.append('Q');}}if (col == n - 1) {String[] strs = new String[n];strs[col] = sb.toString();results.add(strs);} else {ArrayList<String[]> nextResult = createNQueens(n, cols, col + 1);for (String[] strs : nextResult) {strs[col] = sb.toString();results.add(strs);}}cols.remove((Integer) i);}return results;}
- CODE 82: N-Queens
- CODE 81: N-Queens II
- [leet code] N-Queens & II
- 89. Gray Code \ 51. N-Queens \ 52. N-Queens II
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-Queens
- N-queens
- N-Queens
- N-Queens
- 一个关于移位的问题的多种算法求解
- java提高篇(二)-----理解java的三大特性之继承
- 生产订单成本报表
- 三大框架的工作原理(Struts1、Struts2、Spring、Hibernate)
- Poj 3372 Candy Distribution
- CODE 82: N-Queens
- 千万不要得一百分
- 最新版SSH框架简单整合(Struts 2.3.15.2 + Spring 4.0.0 + Hibernate 4.2.6)与整合手记
- 二叉树先序遍历、中序遍历、后续遍历算法
- python操作MySQL数据库(二)
- iOS开发>>>UIImageView连续播放图片,组成动画
-
- android所有控件、ProgressBar 、Android 动画效果、SQLite、四大组件、Android多媒体
- 每天学点Linux--(Ubuntu下的shell版本查询)