1. Bishop Tour (2D arrays)
Bishop Tour
This was similar to Knight Tour but moving the bishop chess piece instead.
The bishop can only move diagonally so we kept track of the current direction
(dr,dc) and updated it whenever the bishop bumped into the edges of the board:
* the row direction, dr, flips between +1 and -1 when the bishop bumps
in the top or bottom edge of the board
* the column direction, dc, flips between +1 and -1 when the bishop bumps
in the left or right edge of the board
The rest of the code is identical to the Knight Tour:
* place the bishop (mark a square)
* decide where to move next
* decide when to stop
We decided to keep running the game as long as the bishop is away from its
starting location.
It is easier to decide when the bishop is at the original location:
curRow == startRow && curCol == startCol [ both positions must be identical]
Then we can express the condition "the bishop is not at the original location":
curRow != startRow || curCol != startCol [ at least one position must be different ]
A common incorrect condition is:
curRow != startRow && curCol != startCol
The incorrect condition insists that both positions must be different.
The do-while Loop
We realized that using while loop with the condition above will stop the
game immediately. It is possible to make the game work with while loop,
but instead we introduced the do-while loop.
The do-while loop is identical to the while loop but it guarantees
that we will go through the loop once.
This allows the bishop to make at least one step away from the starting location.
The implementation
Here is the code. It does not work if the bishop starts at the bottom or at
the right edge of the board (is there a way to fix this?).
Note that when the direction is switched we need to use if-if, not if-else if,
since both directions may need to be updated on the same cycle.
void playBishopTour( int numRows, int numCols, int startRow, int startCol )
{
int[][] board = new int[ numRows ][ numCols ]; // make the board
int curRow = startRow; // track the bishop's location
int curCol = startCol;
int dr = +1; // direction to move (initially SE)
int dc = +1;
int steps = 1;
do
{
board[ curRow ][ curCol ] = steps; // mark the board, redraw
steps++;
drawChessBoard( board );
curRow = curRow + dr; // move the bishop
curCol = curCol + dc;
if ( curRow == board.length - 1 || curRow == 0 ) // need to switch row dir
{
dr = -dr;
}
if ( curCol == board[0].length - 1 || curCol == 0 ) // need to switch col dir
{
dc = -dc;
}
}
while ( curRow != startRow || curCol != startCol ); // not at original?
}