Qwerty
Qwerty

Reputation: 314

Printing all solutions in N-Queen Problem

The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem.

The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.

I wrote function, but it is print only 1 solution. How I can update this function to print all of solutions?

Queen is "q", empty values is "-"

function find_all_arrangements(n) {
    const allRes = [];

    function isValid(row, col, board) {
  // Checks the ← direction
    for(var i=0; i<col; i++){
      if (board[row][i] === "q") {
        return false;
      }
    }

    // Checks the ↖ direction 
    for(var i=row, j=col; i>=0 && j>=0; i--, j--){
      if (board[i][j] === "q") {
        return false;
      }
    }

    // Checks the ↙ direction 
    for(var i=row, j=col; j>=0 && i<n; i++, j--){
      if (board[i][j] === "q") {
        return false;
      }
    }

    return true;
    }

    function find(col, result) {
        if (col === n) {
            allRes.push(result);
      return true;
        }
        for (let i = 0; i < n; i++) {
            if (isValid(i, col, result)) {
                result[i][col] = "q";
                if (find(col + 1, result)) {
          return true;
        }
        result[i][col] = "-";
            }
        }
    return false;
    }

  function generateBoard(n){
    var board=[];
    for(var i=0; i<n; i++){
      board[i]=[];
      for(var j=0; j<n; j++){
        board[i][j]="-";
      }
    }
    return board;
  }

  var board = generateBoard(n);
  find(0, board);
  return allRes;
}

console.log(find_all_arrangements(4))

Upvotes: 1

Views: 2075

Answers (1)

Victor Goh Ka Hian
Victor Goh Ka Hian

Reputation: 167

Almost there, just modify the find function to clone the result array and some tweaking to backtracking:

function find(col, result) {
    if (col === n) {
      // this deep clone the 2d array
      allRes.push(JSON.parse(JSON.stringify(result)));
      return;
    }
    for (let i = 0; i < n; i++) {
        if (isValid(i, col, result)) {
            result[i][col] = "q";
            find(col + 1, result)
            result[i][col] = "-";
        }
    }
}

Upvotes: 4

Related Questions