【发布时间】:2015-08-18 09:40:01
【问题描述】:
我已经实现了 n-queens 问题。但是,与在线解决方案相比,我的组合比实际答案更多。
下面是我的代码
public class Queens
{
static int rows = 5;
static int cols = 5;
public static void main(String[] args)
{
int[] column = {-1,-1,-1,-1,-1};
fun(0, column);
}
/* j is basically each column */
static void fun(int j, int[] column)
{
if(j == cols)
{
System.out.print("success : ");
for(int k = 0;k<column.length;k++)
{
System.out.print(column[k]);
}
System.out.println("");
return;
}
/* Each column could have the queen in any of the rows */
for(int i = 0;i <rows ;i++)
{
if(isValid(column,j,i) == 1)
{
int[] temp = new int[rows];
for(int k = 0;k<column.length;k++)
temp[k] = column[k];
column[j] = i;
fun(j+1,column);
for(int k = 0;k<temp.length;k++)
column[k] = temp[k];
}
}
}
static int isValid(int[] a, int row, int check)
{
int lastindex = 0;
/* check if they're in the same row */
for(int i = 0;i<a.length;i++)
{
if(a[i] == -1)
{
lastindex = i-1;
break;
}
if(a[i] == check)
return 0;
}
/* check if they're in the same diagonal */
if(lastindex >= 0)
{
/* diagonal on the rise */ /* falling diagonal */
if( (a[lastindex] == check-1) || (a[lastindex] == check+1) )
return 0;
}
/* Note : It can't be in the same column since you're selecting only one for each column, the for loop */
return 1;
}
}
这是我对 5 皇后问题的输出。 (在代码中,您可以通过相应地更改行和列的值并更改数组来获得任何 n)
success : 13524
success : 14253
success : 24135
success : 24153 -
success : 25314
success : 31425
success : 31524 -
success : 35142 -
success : 35241
success : 41352
success : 42513 -
success : 42531
success : 52413
success : 53142
但是,在我用来比较输出的online site 中缺少最后标有连字符的那些
请告诉我这四个不一致的原因。 (对于 8-queen,我上面的代码在输出中给出了 5242 个组合,肯定是我在 isValid 函数中做错了)
编辑:非常感谢 vish4071,我现在更改了 isValid() 函数并获得了正确的输出;我不知道每一步都必须检查对角线。
代码
public class Queens
{
static int rows = 8;
static int cols = 8;
public static void main(String[] args)
{
int[] column = {-1,-1,-1,-1,-1,-1,-1,-1};
fun(0, column);
}
/* j is basically each column */
static void fun(int j, int[] column)
{
if(j == cols)
{
System.out.print("success : ");
for(int k = 0;k<column.length;k++)
{
System.out.print(column[k]);
}
System.out.println("");
return;
}
/* Each column could have the queen in any of the rows */
for(int i = 0;i <rows ;i++)
{
if(isValid(column,j,i) == 1)
{
int[] temp = new int[rows];
for(int k = 0;k<column.length;k++)
temp[k] = column[k];
column[j] = i;
fun(j+1,column);
for(int k = 0;k<temp.length;k++)
column[k] = temp[k];
}
}
}
static int isValid(int[] a, int col, int check)
{
for(int i = 0;i<a.length;i++)
{
if(a[i] == -1)
break;
/* check if they're in the same row */
if(check == a[i])
return 0;
/* check if they're in the same diagonal */
if( Math.abs(check-a[i]) == (col-i) )
return 0;
}
/* Note : It can't be in the same column since you're selecting only one for each column, the for loop */
return 1;
}
}
【问题讨论】:
-
原因很简单,你的代码与最优算法不匹配:)
标签: java algorithm backtracking n-queens