10.4 N-Queens

Link: https://oj.leetcode.com/problems/n-queens/

Time: O(n!), Space: O(n)

Approach: DFS

public class Solution {
    //http://huntfor.iteye.com/blog/2070635
    ArrayList<String[]> result = new ArrayList<String[]>();
    public ArrayList<String[]> solveNQueens(int n) {
        int[] cols = new int[n];//the column indices for each Queen in each row
        helper(n, 0, cols);
        return result;
    }
    //place a Queen on each row 
    public void helper(int n, int row, int[] cols){
        if(row == n){
            String[] item = new String[n];
            for(int i = 0; i < n; i++){
                StringBuilder sb = new StringBuilder();
                int col = cols[i];
                for(int j = 0; j < n; j++){
                    if(j == col){
                        sb.append("Q");
                    }
                    else{
                        sb.append(".");
                    }
                }
              item[i] = sb.toString();  
            }
            result.add(item);
            //return;
        }
        for(int j = 0; j < n; j++){//check each column
            if(!isConflict(row, j, cols)){
                cols[row] = j;
                helper(n, row+1, cols);
                cols[row] = 0;//其实这里没必要将m重新赋值的,因为检测到下一个安全位置的时候会把hash[m]覆盖掉的.但是为了更好的体现“回溯”的思想,在这里画蛇添足了
            }
        }
    }
    
    public boolean isConflict(int row, int col, int[] cols){
        if(row == 0) return false;
        for(int i = 0; i < row; i++){//only to check conflict with previous rows
            if(cols[i] == col || (Math.abs(cols[i]-col)== row-i)){
                return true;
            }
        }
        return false;
    }
}

Note: 

If we move cols[row] = j out of the if :

   for(int i = 0; i < n; i++){
            cols[row] = i;
            if(!isConflict(row, i, cols)){
                dfs(n, row+1, cols);
                cols[row] = 0;
            }
        }
We then get the 

Runtime Error Message: Line 28: java.lang.ArrayIndexOutOfBoundsException: 1
Last executed input: 1
 Why?

相关题目:Sudoku Solver


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值