1 year ago
#314296
warlock
N-Queens 2 leetcode question different output
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
This is my code for the n queens question. I cant find any error but my output keeps coming out to be 0. pls help
class Solution
{
public int totalNQueens(int n)
{
List<List<Integer>> result=new ArrayList<>();
function(n,0,result,new ArrayList<Integer>());
return result.size();
}
public void function(int n, int row,List<List<Integer>> result,List<Integer> col)
{
if(n==row)
{
result.add(new ArrayList<>(col));
}
else
{
for(int i=0;i<n;i++)
{
col.add(i);
if(isvalid(col))
{
function(n,row+1,result,col);
}
else
col.remove(col.size()-1);
}
}
}
public boolean isvalid(List<Integer> col)
{
// if(col.size()==1)
// return true;
// int c=col.get(col.size()-1);
int r=col.size()-1;
for(int i=0;i<r;i++)
{
if(col.get(r)==col.get(i) || Math.abs(i-r)==Math.abs(col.get(r)-col.get(i)))
return false;
}
return true;
}
}
java
algorithm
recursion
n-queens
0 Answers
Your Answer