Monday, June 14, 2021

Queen's Challange Part 6 of 6

 Part 6: Forward Checking

Backtracking drastically improved our search for a solution but there was the issue that we would still place queens in positions where they were obviously in conflict. This issue can be removed by simply using the concept of domains. The idea here is that every queen has a domain made up of the tiles that they can occupy. When you place a queen on the board you examine the domains of the queens not yet placed and remove the invalid locations from those domains. Queens are then placed only in tiles still within their domain. The figure below shows the domains for the current step.


This has two important advantages over backtracking. First, you are only checking tiles that are not in conflict with another queen. Second, if a domain for one of the future queens becomes empty then you know immediately that the current solution is not valid and can backtrack.

This does add a bit of complexity as when you backtrack, you need to add back into the other queen’s domains the moves that you had marked as invalid. An easy way to do this, which is the method I will be using for this animation, is to simply have an array for the domain with values indicating when a location has been removed from that domain. This is an inefficient way of doing things. A faster way would be to use bit fields to represent valid moves with the bit-fields pushed onto a stack every domain and pulled from the stack to backtrack. Bit manipulation tends to be hard to read code, so as speed is not a concern due to large delays between frames, I’ll stick with the easier to understand method.

There is a lot involved in the implementation with the first thing done when I was writing this was to display the domains while slowing down the animation speed to allow for easy visualization on what was happening. When domain adjustments were working, I got the game working up to the backtrack step. Finally I implemented the backtracking and was surprised when everything just worked!

The setup for this class was a bit more complicated than the other solvers as we need to create a two-dimensional array to track our domain. We are using -1 to indicate a domain location that is valid, with the depth that a location became invalid for inaccessible tiles.

class ForwardSolver extends BaseSolver {
   
constructor(game) {
       
super(game);
        this
.depth = 0;
        this
.domains = [];
        for
(let y = 0; y < 8; ++y) {
           
let row = [];
            for
(let x = 0; x < 8; ++x) {
                row.
push(-1);
           
}
           
this.domains.push(row);
       
}
    }

As with the backtrack solver, we will need to adjust the placeStepOnBoard method. This is identical to the backtrack solver so we copy that code. Could have inherited from BacktrackSolver to remove duplicate code but it is just three lines and the rest of the class is quite different from the backtrack solver.

placeStepOnBoard() {
   
super.placeStepOnBoard();
    for
(let i = this.depth; i < 7; ++i)
       
this.game.queens[i+1].setVisible(false);
}

Resetting the solver is simply a matter of setting all the domain variables back to the valid value of -1. Next we need to place the starting queen on the board. This is a bit tricky as the locked queen doesn’t really have a depth so we will use a depth of -1 to represent this initialization phase. This is a bit of a kludge but makes the logic of the rest of the solver routines easier to write. The updateDomains method is used to set the domains up with the conflicts caused by the locked queen removed from the other pieces domains. This method will be explained below. Once the locked queen has been accounted for, we set the depth to our 0 starting depth and we are ready to go.

reset() {
   
this.locked = this.game.queens[0].y * 8 + this.game.queens[0].x;
    for
(let y = 0; y < 8; ++y) {
       
let d = y === this.game.queens[0].y ? 0 : -1;
        for
(let x = 0; x < 8; ++x) {
           
this.domains[y][x] = d;
       
}
    }
   
this.depth = -1;
    this
.updateDomains(this.game.queens[0].x, this.game.queens[0].y);
    this
.depth = 0;
    this
.placeStepOnBoard();
}

 

The heart of forward checking is our updateDomains method. This is broken into two separate parts. The first part is where we remove invalid moves from the domains of the queens on rows below the current queen. If the queen being placed is the locked queen then we use the domain level 0 otherwise we use the current domain. We only need to remove moves from rows below the current queen. We know that queen’s can’t be in the same row, o, or diagonal, so these coordinates are calculated based on the distance from the queen that is being placed on the board.

This is where things start to get a little confusing. We can’t just set the domains to invalid but need to check that the tiles we are marking as invalid have not already been marked invalid by a queen placed at a lower depth. This is required to make sure backtracking works as a tile may have more than one queen in conflict so backtracking only restores domain moves that are actually valid. These are simple conditional checks so we make sure the diagonal is on the board and the tile is sto;; viable and if so mark it with the current depth to indicate it is now invalid.

updateDomains(qx,qy) {
   
// remove invalid moves from domain by marking with level
   
let domainLevel = (this.depth < 0) ? 0 : this.depth;

    for
(let y = domainLevel; y < 8; ++y) {
       
if (this.domains[y][qx] < 0)
           
this.domains[y][qx] = domainLevel;
        let
dx1 = qx + y - qy;
        let
dx2 = qx -y + qy;
        if
((dx1 >= 0) && (dx1 < 8) && (this.domains[y][dx1] < 0))
           
this.domains[y][dx1] = domainLevel;
        if
((dx2 >= 0) && (dx2 < 8) && (this.domains[y][dx2] < 0))
           
this.domains[y][dx2] = domainLevel;
   
}
   

Once we have marked the domain variables, we need to actually do the forward check and see that every domain still has a move left. This is a loop through the rows below the placed queen skipping over the locked row if it is encountered. We then loop through the domain for that row exiting if we find a free tile. If there is no valid tile then we set the backtrack flag and exit out of the row loop. If the backtrack flag was set we call backtrack.

    // see if remaining rows still valid
   
let row = domainLevel;
    let
needToBacktrack = false;
    if
(row >= this.game.queens[0].y)
        ++row
   
for (let i = domainLevel; i < 7; ++i) {
       
if (row === this.game.queens[0].y)
            ++row
;
        let
move = false;
        for
(let c = 0; c < 8; ++c) {
           
if (this.domains[row][c] < 0) {
                move =
true;
                break;
           
}
        }
       
if ( ! move) {
            needToBacktrack =
true;
            break;
       
}
        ++row
;
   
}
   
if (needToBacktrack)
       
this.backTrack();
}

Backtracking is easy. We simply loop through all the domains. Any domain set to the current depth level or higher gets set to -1 which makes it a usable tile again. Once this is done we set the depth to a lower depth and are finished.

backTrack() {
   
for (let y = this.depth; y < 8; ++y) {
       
for (let x = 0; x < 8; ++x) {
           
if (this.domains[y][x] >= this.depth)
               
this.domains[y][x] = -1;
       
}
    }
    --
this.depth;
}

 

The nextMove method is a much simpler way of implementing backtrack but only because all of the above work. This method finds the row associated with this depth. Once on the row, we loop over the domain for the row until we find the available tile. If we then use the updateDomains method to place the queen for this depth on that tile. If there is no spots available for our queen we backtrack.

nextMove() {
   
let row = this.depth;
    if
(this.game.queens[0].y <= row)
        ++row
;
    let
moved = false;
    for
(let c = 0; c < 8; ++c) {
       
if (this.domains[row][c] < 0) {
           
this.moveable[this.depth] = row*8+c;
            this
.domains[row][c] = this.depth;
           
++this.depth;
            this
.updateDomains(c, row);
           
moved = true;
            break;
       
}
    }
   
if (!moved)
       
this.backTrack();

 For debugging, we then draw the domains by looping over the domains for all tiles on the board and if the domain is -1 set a highlight tile in the game to our highlight color. While this was meant for my own debugging but as the effect is really cool, I decided to leave it in the game.

    // show domains
   
for (let y = 0; y < 8; ++y) {
       
for (let x = 0; x < 8; ++x) {
           
if (this.domains[y][x] === -1) {
               
this.game.boardHighlights[y * 8 + x].setBackgroundColor("rgba(0,0,128,.5)");
                this
.game.boardHighlights[y * 8 + x].setVisible(true);
           
}
        }
    }

}

Running this only takes a few seconds which is an improvement. There is still some situations where lower board positions have domains that are clearly in conflict with each other but this is really very slim improvements so I will stop my solver series here. For those of you who wish to progress to the next step, you will want to look into arc consistency.


Friday, May 14, 2021

Queen's Challenge - Part 5 of 6

 Part 5 – Backtrack Solver

While a smarter brute force method had a drastic effect on the performance of our solver, we were still trying out a huge number of combinations that were clearly not going to work. If only there was some way to eliminate the bulk of these clearly invalid moves. There is an approach called backtrack solving, which attempts to prune as many searches as possible. This is often depicted as a tree, so lets represent our first few rows as a tree.



As you can see, for each of the moves in the first row of the board, each piece of the second row has 8 moves it can make. For each combination of the first and second piece, there is an additional 8 moves for that combination, and so on. If, however, the first row and the second row are in conflict, then all the moves underneath the second row position are also in conflict so the entire branch underneath that move can be eliminated. This leads to a very simple process. For whatever row we are working on, lets call it depth as that is the generic term for a tree search, we try the first available position. If that position is not in conflict with any other queens, we go to the next row otherwise we go to the next position. If for a given row there is no valid position, we backtrack by going to the previous row and moving it to the next position. Repeat until all pieces are placed on the board or there are no more possible moves to try (no solution to the problem).

Implementation of a backtrack solver is not that much more difficult than brute-force methods but does require some slight modifications to how the solver works. Instead of placing all the pieces on the board, we only place the locked piece and a queen for each of the rows we have processed. We will use the term depth to represent how many of our pieces we have placed. As I am a programmer, the count will start at 0.

class BacktrackSolver extends BaseSolver {
   
constructor(game) {
       
super(game);
        this
.depth = 0;
   
}

 

We can change how pieces are placed on the board by overriding the placeStepOnBoard method and making all the pieces beyond our current depth invisible. Some minor changes to reflect this change were made to the isBoardSolved method but I won’t go over the details here.

    placeStepOnBoard() {
       
super.placeStepOnBoard();
        for
(let i = this.depth+1; i < 7; ++i)
           
this.game.queens[i+1].setVisible(false);
   
}


 

The reset method is very simple as we just need to set the depth to 0 and start our first queen off on either the first row or second row if the first row is occupied by the locked queen.

reset() {
   
this.locked = this.game.queens[0].y * 8 + this.game.queens[0].x;
    let
lockedRow = this.game.queens[0].y;
    if
(lockedRow === 0)
       
this.moveable[0] = 8;
    else
        this
.moveable[0] = 0;
    this
.depth = 0;
    this
.placeStepOnBoard();
}

 

Because we need to check if a queen is in conflict with another queen, we will take advantage of the game logic we already have within the game instead of re-writing the logic. This can be a bit confusing as the locked queen is queens[0] while our queens are 1 through seven but you only need to add 1 to the current depth to find the queen we are working with. We first check to see if the queen we are looking at is in a valid position assuming it is not valid if we are backtracking. If the board is in a valid state then we start the next depth by placing the next queen in the starting column of it’s row, skipping over the locked row when necessary and we have finished our move. If the board is not in a valid position, then we stay at the same depth moving our queen to the next column of the row. If the queen is able to be moved, we are done. On the other hand, if the queen is at the end of the row, we need to backtrack so we reduce our depth and repeat the above.

    nextMove() {
       
let moved = false;
        let
backtrack = false;
        while
( ! moved) {
           
let queen = this.game.queens[this.depth+1];
           
queen.setVisible(false);
            if
((!backtrack) && (this.game.canEnterTile(queen.x, queen.y))) {
               
// spawn next depth
               
++this.depth;
                let
lockedRow = this.game.queens[0].y;
                this
.moveable[this.depth] = (queen.y+1) * 8;
                if
((queen.y+1) === lockedRow)
                   
this.moveable[this.depth] += 8;
               
moved = true;
           
} else {
               
if (queen.x < 7) {
                   
this.moveable[this.depth] += 1;
                    
moved = true;
               
} else {
                    backtrack =
true;
                   
--this.depth;
               
}
            }
        }
    }
}

 

Running the solver will usually result in a solution in under a minute, which is really good when you consider that we are only doing 10 steps per second. So, mathematically speaking, how long should this take? Best case would be 7 steps. The theoretical worst case is 8^7 for 2,097,152 which happens to be the same as the brute-force lines method. For this particular problem, we know that we will be pruning a lot of branches so our results will be significantly better than worst case, but calculating this is not a trivial matter so will leave the calculations to the more mathematically inclined.

Can we improve things further? Watching the results, you will notice that many of the boards checked are positions that are obviously bad based on the above pieces. If only there was a way of just checking potentially valid tiles. We will call this forward checking and look at it next time.

Thursday, April 15, 2021

Queen's Challenge - Part 4 of 6

 Part 4 – One Queen Per Row

Last time we saw a big problem with the brute force approach which we saw that queens were often placed on the same horizontal line as other queens which we know is not possible. This is a problem that can easily be rectified by imposing a constraint on where we are allowed to place the queens.  Ultimately, we are still going to be brute forcing the solution but by removing the most obvious issues with brute force.

The term constraint is simply mathematical speak about a rule restricting the values a variable can hold based on the value in other variables. Having more than one queen in a given row is clearly not valid so we can eliminate all boards where there are multiple queens on a single line. Applying the constraint that each queen must be on a unique row drastically will improve the performance of our search for a solution.

Creating our row-based brute force solver is simple enough as we can just extend the BaseSolver to get much of the logic. The only things we then need to implement is the reset and the next move methods and they are very similar to the brute force solver.

class RowBruteSolver extends BaseSolver {
   
constructor(game) {
       
super(game);
   
}

   
reset() {
       
this.locked = this.game.queens[0].y * 8 + this.game.queens[0].x;
        let
lockedRow = this.game.queens[0].y
       
let spot = 0;
        for
(let i = 0; i < 7; ++i) {
           
if (i === lockedRow)
                spot +=
8;
            this
.moveable[i] = spot;
           
spot += 8;
       
}
    }

 

As with the brute force solver, we set the locked tile to be the tile number of the tile based on the row and column of the locked tile in the game. We need to know which row this tile is on, which is just the y coordinate of the locked queen. As each row of tiles has 8 tiles on it, we know that the tile number will be 8*the row but we know we need to skip the row that row that the locked queen is on. To do this we use a spot variable that starts at 0 and if the current row is the same row as the locked row increases the spot by 8 to move the starting spot to the first (0) column of the next row. The queen is set and we update the spot for the next queen by adding 8 to it.

 

    nextMove() {
       
let pieceToMove = 0;
        for
(let i = 6; i >= 0; --i) {
           
let nextPos = this.moveable[i] + 1;
            if
((nextPos % 8) > 0) {
                pieceToMove = i
;
                this
.moveable[i] = nextPos;
                break;
           
}
        }
       
for (let i = pieceToMove+1; i < 7; ++i) {
           
this.moveable[i] = Math.floor(this.moveable[i] / 8)*8;
       
}
    }
}

 

The nextMove method tries to move the last row’s queen to the next column and if that move results in the queen going off the board , moves up the list row by row until it finds a queen that it can move to the right without going off the board. Once that has been done, we simply set the queens below it to the first tile of that column.

Watching the results of this solver clearly shows an improvement from the first solver. If you are patient and can wait a few hours, you can even see a solution to the game. Watching for a minute or so will quickly show us the next issue that we need to solve. We still are placing queens in locations were they are in conflict with each other and then processing all the queens below the conflicting queens even though we know that none of those potential layouts will result in a valid solution. Still this is a big improvement over the brute force approach.

From a worst-case perspective, we know that there are 7 queens with each queen having 8 possible locations so that would be 8^7 possible boards that need to be examined. While 2,097,152 boards is certainly better than 994,596,970,221 it is still quite a bit of work. We can do even better by finding a way to remove all those unnecessary searches. But how can we do this? A simple change to our solver will allow us to eliminate entire branches of moves so we don’t waste time testing moves that can’t possibly work as we will discover in the next part.