【Leetcode】N-Queens I

本文详细介绍了使用递归回溯法解决N皇后问题的Java算法实现过程,包括解决方案生成、有效性验证和棋盘打印等关键步骤。

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:

1.http://blog.youkuaiyun.com/u011095253/article/details/9158473

</pre><pre name="code" class="java">public class Solution {
    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> res = new ArrayList<String[]>();
        int[] loc = new int[n];
        dfs(res,loc,0,n);
        return res;
    }
    
    public void dfs(ArrayList<String[]> res, int[] loc, int cur, int n){
        if(cur==n) 
            printboard(res,loc,n);
        else{
            for(int i=0;i<n;i++){
                loc[cur] = i;
                if(isValid(loc,cur))
                    dfs(res,loc,cur+1,n);
            }
        }
    }
    
    public boolean isValid(int[] loc, int cur){
        for(int i=0;i<cur;i++){
            if(loc[i]==loc[cur]||Math.abs(loc[i]-loc[cur])==(cur-i))
                return false;
        }
        return true;
    }
    
    public void printboard(ArrayList<String[]> res, int[] loc, int n){
        String[] ans = new String[n];
        for(int i=0;i<n;i++){
            String row = new String();
            for(int j=0;j<n;j++){
                if(j==loc[i]) row += "Q";
                else row += ".";
            }
            ans[i] = row;
        }
        res.add(ans);
    }
}


2. http://blog.youkuaiyun.com/linhuanmars/article/details/20667175

public ArrayList<String[]> solveNQueens(int n) {
    ArrayList<String[]> res = new ArrayList<String[]>();
    helper(n,0,new int[n], res);
    return res;
}
private void helper(int n, int row, int[] columnForRow, ArrayList<String[]> res)
{
    if(row == n)
    {
        String[] item = new String[n];
        for(int i=0;i<n;i++)
        {
            StringBuilder strRow = new StringBuilder();
            for(int j=0;j<n;j++)
            {
                if(columnForRow[i]==j)
                    strRow.append('Q');
                else
                    strRow.append('.');
            }
            item[i] = strRow.toString();
        }
        res.add(item);
        return;
    }
    for(int i=0;i<n;i++)
    {
        columnForRow[row] = i;
        if(check(row,columnForRow))
        {
            helper(n,row+1,columnForRow,res);
        }
    }
}
private boolean check(int row, int[] columnForRow)
{
    for(int i=0;i<row;i++)
    {
        if(columnForRow[row]==columnForRow[i] || Math.abs(columnForRow[row]-columnForRow[i])==row-i)
            return false;
    }
    return true;
}

3. 还有经常出现的 水印人生:http://gongxuns.blogspot.com/2012/12/leetcoden-queens.html

public class Solution {
    public ArrayList<String[]> solveNQueens(int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        assert(n>=0);
        ArrayList<String[]> res = new  ArrayList<String[]>();
        solveNQueues(1, new int[n], res);
        return res;
    }
    
    public void solveNQueues(int k, int[] solu, ArrayList<String[]> res){
        int n= solu.length;
        main:
        for(int i=0;i<n;i++){
            for(int j=0;j<k-1;j++)
                if(solu[j]==i || Math.abs(solu[j]-i)==Math.abs(j-k+1)) continue main;   
            solu[k-1]=i;
            if(k==n){
                String[] temp = new String[n];
                for(int l=0;l<n;l++){
                    temp[l]=generateRow(n,solu[l]+1);
                }
                res.add(temp);
            }else
                solveNQueues(k+1,solu,res);
        }
    }
    
    public String generateRow(int n, int k){
        assert(k>0 && k<=n);
        StringBuilder res = new StringBuilder("");
        for(int i=0;i<k-1;i++){
            res.append(".");
        }
        res.append("Q");
        for(int i=k;i<n;i++){
            res.append(".");
        }
        return res.toString();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值