Skip to content

Chess Knight

Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform.

The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from it. The complete move therefore looks like the letter L. Check out the image below to see all valid moves for a knight piece that is placed on one of the central squares.

Image Credit : Code Signal

Example

  • For cell = "a1", the output should be

    chess_knight(cell) = 2
    Image Credit : Code Signal
  • For cell = "c2", the output should be

    chess_knight(cell) = 6
    Image Credit : Code Signal

Input/Output

  • [execution time limit] 4 seconds (py3)

  • [input] string cell

    String consisting of 2 letters - coordinates of the knight on an 8 × 8 chessboard in

Solution

py
def move_north(row):
    return row + 2 <= 8


def move_south(row):
    return row - 2 >= 1


def move_east(col):
    return col + 2 <= 8


def move_west(col):
    return col - 2 >= 1


def move_left(squares):
    if squares - 1 >= 1:
        return 1
    return 0


def move_right(squares):
    if squares + 1 <= 8:
        return 1
    return 0


def chess_knight(cell):
    col = ord(cell[0]) - 96
    row = int(cell[1])

    moves = 0

    if move_north(row):
        moves += move_left(col) + move_right(col)

    if move_south(row):
        moves += move_left(col) + move_right(col)

    if move_east(col):
        moves += move_left(row) + move_right(row)

    if move_west(col):
        moves += move_left(row) + move_right(row)

    return moves


print(chess_knight('d5'))
js
function chessKnight(cell) {
  let count = 0;
  let x = cell.charCodeAt(0) - 96;
  let y = parseInt(cell[1]);
  let moves = [
    [x + 1, y + 2],
    [x + 2, y + 1],
    [x + 2, y - 1],
    [x + 1, y - 2],
    [x - 1, y - 2],
    [x - 2, y - 1],
    [x - 2, y + 1],
    [x - 1, y + 2],
  ];
  for (let i = 0; i < moves.length; i++) {
    if (moves[i][0] > 0 && moves[i][0] < 9 && moves[i][1] > 0 && moves[i][1] < 9) {
      count++;
    }
  }
  return count;
}

my thoughts are neither my employer's nor my wife's