首页 > 解决方案 > 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

标签: javarecursioniteration

解决方案


推荐阅读