Finding the possible positions of a knight on a chess board with C#

Given the position of a knight on a chess board in column,row notation (i.e. “a1”), return the total number of possible positions the knight can move to.

 

 

 

 

 

 

 

 

int chessKnight(string cell)
{
int numberOfPositions = 0;
// get the current position
int row = cell[0]; // 97 = 'a' = 0 position.
int column = Convert.ToInt32(cell[1].ToString());//1 is 0 position.
//check if we can move up and right from here
if (positionIsValid(row + 1, column + 2))
{
numberOfPositions++;
}
//check if we can move up left
if (positionIsValid(row - 1, column + 2))
{
numberOfPositions++;
}
//check if we can move down and right from here
if (positionIsValid(row + 1, column-2))
{
numberOfPositions++;
}
//check if we can move down and left
if (positionIsValid(row - 1, column - 2))
{
numberOfPositions++;
}
//check if we can move left and up
if (positionIsValid(row - 2, column + 1))
{
numberOfPositions++;
}
//check if we can move left and down
if (positionIsValid(row - 2, column - 1))
{
numberOfPositions++;
}
//check if we can move right and up
if (positionIsValid(row + 2, column + 1))
{
numberOfPositions++;
}
//check if we can move right and down
if (positionIsValid(row + 2, column - 1))
{
numberOfPositions++;
}
return numberOfPositions;
}


bool positionIsValid(int row, int column)
{
// the columns go from 1 to 8, the the rows go from 97 to 104 (ascii chars)
if (column >= 1 && column <= 8 && row >= 97 && row <= 104)
{
return true;
}
return false;
}

Tom

Leave a comment

Your email address will not be published. Required fields are marked *