The following is my solution to a problem. While it works - I want to learn how to optimize this in a much better way (I'm new to C++). My original idea was the use a map
to map the r,c
pairs and then test those but hoping someone can help optimize this for me.
Write a function using a grid of string and two row/column pairs (r1, c1), (r2, c2) which returns true if there is a knight at chess board square (r1, c1) who can move to empty square (r2, c2). For your function to return true, there must be a knight at square (r1, c1), and the square at (r2, c2) must store an empty string, and both locations must be within the bounds of the grid. A knight makes an "L" shaped move, going 2 squares in one dimension and 1 square in the other. i.e. if the chess board (1, 2) stores "knight", then the call of knightMoves(board, 1, 2, 2, 4) returns true.
Here is my current solution
bool knightMoves(Grid<string>& board, int r1, int c1, int r2, int c2);
int main() {
//create a fake board
Grid<string> board(7,7);
board[1][2] = "knight";
board[3][1] = "rock";
board[0][4] = "king";
//fire the function
bool result = knightCanMove(board, 1, 2, 2, 4);
cout << result << endl;
return 0;
}
bool knightMoves(Grid<string>& board, int r1, int c1, int r2, int c2) {
bool canMove = false;
string knight = "knight";
//within grid bounds
if(r1 > board.numRows() || c1 > board.numCols()) return false;
if(r2 > board.numRows() || c2 > board.numCols()) return false;
//test whether the co-ords match a knight string,
//if yes, continue
if (board[r1][c1] == knight) {
if(board[r1 + 2][c1 + 1] == "" && r1+2 == r2 && c1+1 == c2) {
canMove = true;
}
if(board[r1 + 2][c1 - 1] == "" && r1+2 == r2 && c1-1 == c2) {
canMove = true;
}
if(r1 >= 2 && board[r1 - 2][c1 + 1] == "" && r1-2 == r2 && c1+1 == c2) {
canMove = true;
}
if(r1 >= 2 && board[r1 - 2][c1 - 1] == "" && r1-2 == r2 && c1-1 == c2) {
canMove = true;
}
if(board[r1 + 1][c1 + 2] == "" && r1+1 == r2 && c1+2 == c2) {
canMove = true;
}
if(c1 >= 2 && board[r1 + 1][c1 - 2] == "" && r1+1 == r2 && c1-2 == c2) {
canMove = true;
}
if(board[r1 - 1][c1 + 2] == "" && r1-1 == r2 && c1+2 == c2) {
canMove = true;
}
if(c1 >= 2 && board[r1 - 1][c1 - 2] == "" && r1-1 == r2 && c1-2 == c2) {
canMove = true;
}
}
return canMove;
}