LeetCode51. N-Queens52. N-Queens II

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.
这道题我参考了https://blog.csdn.net/u013564276/article/details/51244581这位博主的思想,用一维数组来存储皇后的位置。具体算法的解释可以看原博主,介绍的很清楚,对我很有帮助。
import java.util.*;
public class Solution{
    public List<List<String>> solveNQueens(int n) {
        List<List<String>>res=new ArrayList<>();
        int []queenplace=new int [n];
        placeQueen(queenplace,0,n,res);
        return res;
    }
    public void placeQueen(int []queenplace,int row,int n,List<List<String>> res)
    {
        for(int col=0;col<n;col++)
        {
            if(isValid(queenplace,row,col))
            {
                queenplace[row]=col;
                placeQueen(queenplace,row+1,n,res);
            }
        }
        if(row==n)
        {
            ArrayList<String>list=new ArrayList<>();
            for(int i=0;i<n;i++)//控制行数
            {        
                String str="";
                for(int col=0;col<n;col++)
                {                  
                    if(queenplace[i]==col)
                        str+="Q";
                    else
                        str+=".";
                }
                list.add(str);
            }
            res.add(list);
        }
    }
    public static boolean isValid(int []queenplace,int row,int col)
    {
        for(int i=0;i<row;i++)
        {
            if(col==queenplace[i])
                return false;
            if(col==queenplace[i]+row-i)
                return false;
            if(col==queenplace[i]-row+i)
                return false;
        }
        return true;
    }
}
第52题就是计算一共有多少种n皇后问题方案,只要在原来的基础上把return res改成return res.size()即可。
当然第52题也可以用一种取巧的方法。
int totalNQueens(int n) {
    int ans[] = {0, 1, 0, 0, 2, 10, 4, 40, 92, 352};
    return ans[n];
}






1
import java.util.*;
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值