9.9 N queen I and II leetcode 原题

16 篇文章 0 订阅
9 篇文章 0 订阅

参考来源//http://blog.csdn.net/u011095253/article/details/9158473

http://www.cnblogs.com/springfor/p/3870944.html

public class Solution {
    //http://blog.csdn.net/u011095253/article/details/9158473
    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> res = new ArrayList<String[]>();
        int [] loc = new int[n];
        if(n<=0) return null;
        helper(res,loc,n,0);
        return res;
    }
    
    private void helper( ArrayList<String[]> res, int[] loc, int n, int curRow){  
        
        if(n==curRow) {
            printbrd(res, loc,n);
            return;}
        
        else{
            for(int i=0; i<n; i++){   // test the col position of curRow's queen
               loc[curRow] = i;
               if(isValid(loc, curRow)) 
                   helper(res, loc, n, curRow+1);  // move to next row's queen
                // else test next i's position
             }   
        }
    }
    
    private boolean isValid(int[] loc, int curRow){
       // if(curRow==1) return true;
        for(int i=0;i<curRow;i++){
            if(loc[i]==loc[curRow] || Math.abs(loc[i]-loc[curRow] )==curRow-i)
                return false;
        }
        return true;
    }
    
    private void printbrd(ArrayList<String[]> res, int[] loc, int n){
        String [] soln = new String [n] ;
        for(int i=0;i<n;i++){
            String tmp = new String();
            for(int j=0;j<n;j++){
                if(loc[i]!=j)
                   tmp += ".";
                else
                    tmp += "Q";
                
            }
            soln[i] = tmp;
        }
        res.add(soln);
        
    }
    
}


第二道题目就是统计有多少种方法,改高亮处

public class Solution {
    int res;
    public int totalNQueens(int n) {
        res = 0;
        if(n<=0) return 0;
        int[] loc = new int[n];
        helper(n, loc, 0);
        return res;
    }
    
    public void helper(int n, int[] loc, int curRow){
        if(curRow==n) res++;
        else{
            for(int i=0;i<n;i++){
                loc[curRow]=i;
                if(isValid(loc, curRow))
                    helper(n,loc,curRow+1);
            }
        }
        
    }
    
    public boolean isValid(int [] loc, int curRow){
        if(curRow==0) return true;
        for(int i=0;i< curRow; i++){
            if(loc[i]==loc[curRow]||Math.abs(loc[i]-loc[curRow])==curRow-i)
            return false;
        }
        return true;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值