【Leetcode】N-Queens (Backtracking)
来源:互联网 发布:儿童模式软件下载 编辑:程序博客网 时间:2024/05/21 04:18
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.."]]N皇后问题的基本思路就是回朔法,往每一个格子放棋子,如果是合法的就继续,如果不合法就撤掉
用一维数组解这种题的时候,可以忽略掉撤掉的情况,因为当用一维数组的时候,只存在放与不放的问题,不存在放与撤掉的问题
代码如下
来自Code_Ganker
public ArrayList<String[]> solveNQueens(int n) {ArrayList<String[]> result = new ArrayList<String[]>();if (n <= 0)return result;int[] column = new int[n];helper(n, 0, column, result);return result;}public void helper(int n, int row, int[] column, ArrayList<String[]> result) {if (n == row) {String[] temp = new String[n];for (int i = 0; i < n; i++) {StringBuilder strRow = new StringBuilder();for (int j = 0; j < n; j++) {if (column[i] == j)strRow.append("Q");elsestrRow.append(".");}temp[i] = strRow.toString();}result.add(temp);return;}for (int i = 0; i < n; i++) {column[row] = i;if (check(row, column))helper(n, row + 1, column, result);}}public boolean check(int row, int[] column) {for (int i = 0; i < row; i++) {if (column[i] == column[row]|| Math.abs(column[row] - column[i]) == (row - i))return false;}return true;}
0 0
- 【Leetcode】N-Queens (Backtracking)
- 【Leetcode】N-Queens II (Backtracking)
- leetcode N-Queens/N-Queens II, backtracking, hdu 2553 count N-Queens, dfs
- 【LeetCode】N-Queens && N-Queens II
- leetcode N-Queens & N-Queens II
- Leetcode: N-Queens && N-Queens II
- 【Leetcode】【python】N-Queens/N-Queens II
- LeetCode: N-Queens II
- LeetCode: N-Queens
- LeetCode : N-Queens
- LeetCode : N-Queens II
- [Leetcode] N-Queens II
- leetcode 72: N-Queens
- LeetCode 38: N-Queens
- 【leetcode】N-Queens II
- 【leetcode】N-Queens
- LeetCode: N Queens II
- [LeetCode]N-Queens
- oracle创建实例化数据库或者连接别的远程主机数据库提示“无监听程序”的解决办法
- maven手动上传快照版本jar命令
- adb logcat 查看日志
- C语言关键字
- Google Java编程风格指南
- 【Leetcode】N-Queens (Backtracking)
- 关于WAMP2.4连接SQLserver 2008
- android开发中遇到sqlite3 not found
- linux2.6设备驱动编写
- Android--Dialog(AlertDialog)
- SVN命令使用详解
- 基本数据型态转换成 String,String 转换成 数字的基本数据型态
- Effective Java Item7:Avoid Finalizers,解释为什么finalize是不安全的,不建议使用
- IIS+PHP+MYSQL环境下,数据库导入问题