N-Queens Relationed Quesiton


  • 0
    J

    I run the following code on eclipse and it shows right answer, well every time I run it on leetcode, the input 2 get an out put [["Q"]]. Hope someone could help me~

    public class Solution {
    public static ArrayList<String[]> ret = new ArrayList<String[]>();
    public int totalNQueens(int n) {
        if(n<1){
            return 0;
        }
        String[] rows = new String[n];
        int row = 0;
        bfsNQueen(row,n, rows, ret);
        return ret.size();
    }
    public void bfsNQueen(int row, int n, String[] rows, ArrayList<String[]> ret) {
        if(row == n) {
            ret.add(rows.clone());// ***** .clone()
            return;
        }
        for(int col = 0; col<n; col++){
            if( isValid(col, row, rows) ){
                char[] tmp = new char[n];
                Arrays.fill(tmp, '.'); // ***** Arrays.fill()
                tmp[col] = 'Q';
                rows[row] = String.copyValueOf(tmp); // ***** String.copyValueOf()
            }
        }
        return;
    }
    public boolean isValid(int col, int curRow, String[] rows){
        for(int i=0; i<curRow; i++){
            int curCol = rows[i].indexOf("Q");
            if (col==curCol)
              return false;
            if(Math.abs(i-curRow)==Math.abs(col-curCol))
              return false;
        }
        return true;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.