转载:递归算法学习系列之八皇后问题
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.."] ]
java解法如下所示:
public class Solution { public void dfs(List<List<String>> res, List<String> list, Set<Integer> col, Set<Integer> diag1, Set<Integer> diag2, int row, int n){ if(row==n){ res.add(new ArrayList<String>(list)); return; } //遍历该行的所有列 for(int i=0;i<n;i++){ if(col.contains(i)||diag1.contains(row+i)||diag2.contains(row-i)) continue; col.add(i); diag1.add(row+i); diag2.add(row-i); char[] rowChar = new char[n]; Arrays.fill(rowChar, '.'); rowChar[i] = 'Q'; String rowString = new String(rowChar); list.add(rowString); //继续搜索下一行 dfs(res, list, col, diag1, diag2, row+1, n); //搜索完成后释放所用资源 list.remove(list.size()-1); col.remove(i); diag1.remove(row+i); diag2.remove(row-i); } } public List<List<String>> solveNQueens(int n) { List<List<String>> res = new ArrayList<List<String>>(); if(n==0) return res; Set<Integer> col = new HashSet<Integer>(); //列集 Set<Integer> diag1 = new HashSet<Integer>(); //正对角线集 Set<Integer> diag2 = new HashSet<Integer>(); //副对角线集 List<String> list = new ArrayList<String>(); //用于存放每一种情况 dfs(res, list, col, diag1, diag2, 0, n); return res; } }