Task
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.
Example
-
For
cell = "a1"
, the output should be
chessKnight(cell) = 2
. -
For
cell = "c2"
, the output should be
chessKnight(cell) = 6
.
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 chess notation.
Guaranteed constraints:cell.length = 2
,'a' ≤ cell[0] ≤ 'h'
,1 ≤ cell[1] ≤ 8
. -
[output] integer
My Solution
def chessKnight(cell):
move = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]
arrive = [chr(ord(cell[0]) + i[0]) + str(int(cell[1]) + i[1]) for i in move]
valid_x = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
valid_y = [str(i) for i in range(1, 9)]
count = 0
for position in arrive:
if (position[0] in valid_x) and (position[1:] in valid_y):
count += 1
return count