10.4 N-Queens

来源:互联网 发布:主播网络活动策划书 编辑:程序博客网 时间:2024/06/08 12:52

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: 1Last executed input:1 Why?

相关题目:Sudoku Solver


0 0
原创粉丝点击