java - How can I convert NQueen problem recursion to iterative?
问题描述
I'm trying to convert recursive Nqueen problem solution into iterative solution.
I was trying to change my code by using "While" in "solveNQforThisColumn" instead of using recursive function.
'
public class NqueenIter1 {
static final int NN = 4;
public static boolean isSafePositionQ (int board[ ][ ], int row, int col
) {
//check this row on left
for(int cCnt = 0; cCnt < col; cCnt++) {
if(board[row][cCnt]==1) {
return false;
}
}
//check upper diagonal on left
for(int rCnt = row, cCnt = col; rCnt>=0 && cCnt >=0;rCnt-- , cCnt--) {
if(board[rCnt][cCnt] ==1)
return false;
}
//check lower diagonal on left
for(int rCnt = row, cCnt = col; rCnt < NN && cCnt >=0;rCnt++ , cCnt--) {
if(board[rCnt][cCnt] ==1)
return false;
}
return true;
}
public static boolean solveNQforThisColumn( int board[ ][ ], int col ) {
while(col<NN) {
for(int rowCnt=0;rowCnt<NN;rowCnt++) {
if(isSafePositionQ(board,rowCnt,col)) {
board[rowCnt][col] = 1;
}
}
col ++;
}
if(col==NN) {
return true;
}
return false;
}
public static void main(String[] args) {
int board[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 }
};
if(!solveNQforThisColumn(board, 0)) {
System.out.println("cannot solve the puzzle");
return;
}
printSolution(board);
return;
/* A utility function to print solution */
}
public static void printSolution( int board[][] ) {
for(int row=0;row<NN;row++) {
for(int col=0;col<NN;col++) {
System.out.print(" "+board[row][col]+" ");
}
System.out.println();
}
}
}
`
I expect the output of
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
but the actual output is
1 0 0 0
1 0 0 0
1 0 0 0
1 0 0 0
解决方案
推荐阅读
- git - 寻找一个在关闭文件时自动提交 git 的文本编辑器
- email - BIND DKIM 语法错误
- javascript - 我想在这段代码中显示 Fetched API
- geode - 获取 java.lang.IllegalStateException:无法在定位器中创建区域
- linux - 无法使用 ffmpeg 录制窗口
- angular - 带有静态数据的材料设计数据表布局
- javascript - jQuery自定义手风琴,关闭其他打开的li
- c# - 即使在文本框中没有输入任何内容,C# 我也在尝试进行自动完成显示
- dart - Dart build_runner 只能扫描/读/写 web/ 目录下的文件?
- java - 为什么在 Java 中会发生这种情况?