N-Queens N皇后问题@LeetCode

经典的8皇后,递归回溯可解。同时还学了StringBuilder里面一个setCharAt()很方便的方法。


package Level4;

import java.util.ArrayList;
import java.util.Arrays;

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

http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png

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 class S51 {

	public static void main(String[] args) {
		System.out.println(solveNQueens(4));
	}

	public static ArrayList solveNQueens(int n) {
		ArrayList ret = new ArrayList();
		int[] queenList = new int[n];
		placeQueen(queenList, 0, n, ret);
		return ret;
	}
	
	// 递归回溯8皇后,关键记录下到达了哪一行了
	public static void placeQueen(int[] queenList, int row, int n, ArrayList ret){
		// Base Case, 已经完成任务了
		if(row == n){
			StringBuilder[] sol = new StringBuilder[n];
			
			// 对数组内每一个对象都要new出其对象
			for(int i=0; i


这道题因为要求出全部可能,所以rec函数就没有返回值。如果只要求出一种,返回值就设为boolean,在里面当检查到一种情况为true时就直接返回,只有当检查完所有可能性后才return false (比如sudoku solver)

public class Solution {
    
    public static List solveNQueens(int n) {
        List list = new ArrayList();
        StringBuilder[] sb = new StringBuilder[n];
        String s = "";
        for(int i=0; i list, StringBuilder[] sb, int n, int level) {
        if(level == n) {
            String[] ss = new String[n];
            for(int i=0; i




你可能感兴趣的:(Leetcode,LeetCode专栏)