1D array solution Java version for reference


  • 4
    K

    N-Queen solution Java version using one dimentional array colQ[] to store indices of the rows. Same logic , different language for your reference.

    public class Solution {
    
    List<String[]> result = new LinkedList<String[]>();
    public List<String[]> solveNQueens(int n) {
        int[] colQ = new int[n];
        findNQ(colQ,0);
        return result;
    }
    
    public void findNQ(int[] colQ, int curcol)
    {
        if(curcol == colQ.length) result.add(getOutput(colQ));
        for(int j = 0; j < colQ.length; j++)
        {
            if(isSafe(colQ,j,curcol))
            {
                colQ[curcol] = j;
                findNQ(colQ,curcol+1);
            }
        }
    }
    
    public boolean isSafe(int[] colQ, int row, int curcol)
    {
        int i = 0;
        int j = 0;
        for(i = curcol-1, j = 1; i >= 0; i--, j++)
        {
            if(row == colQ[i] || row+j == colQ[i] || row-j == colQ[i]) return false;
        }
        return true;
    }
    
    public String[] getOutput(int[] colQ)
    {
        String[] outstr = new String[colQ.length];
        StringBuilder strbd = new StringBuilder();
        for(int i = 0; i < colQ.length; i++) strbd.append('.');
        for(int i = 0; i < colQ.length; i++)
        {
            strbd.setCharAt(i,'Q');
            outstr[colQ[i]] = strbd.toString();
            strbd.setCharAt(i,'.');
        }
        return outstr;
    }
    
    }

Log in to reply
 

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