Back to Freecodecamp

Challenge 160: Knight Moves

curriculum/challenges/english/blocks/daily-coding-challenges-python/6939b873185d8e00d453563f.md

latest2.4 KB
Original Source

--description--

Given the position of a knight on a chessboard, return the number of valid squares the knight can move to.

A standard chessboard is 8x8, with columns labeled A through H (left to right) and rows labeled 1 through 8 (bottom to top). It looks like this:

A8B8C8D8E8F8G8H8
A7B7C7D7E7F7G7H7
A6B6C6D6E6F6G6H6
A5B5C5D5E5F5G5H5
A4B4C4D4E4F4G4H4
A3B3C3D3E3F3G3H3
A2B2C2D2E2F2G2H2
A1B1C1D1E1F1G1H1

A knight moves in an "L" shape: two squares in one direction (horizontal or vertical), and one square in the perpendicular direction.

This means a knight can move to up to eight possible positions, but fewer when near the edges of the board. For example, if a knight was at A1, it could only move to B3 or C2.

--hints--

knight_moves("A1") should return 2.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("A1"), 2)`)
}})

knight_moves("D4") should return 8.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("D4"), 8)`)
}})

knight_moves("G6") should return 6.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("G6"), 6)`)
}})

knight_moves("B8") should return 3.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("B8"), 3)`)
}})

knight_moves("H3") should return 4.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(knight_moves("H3"), 4)`)
}})

--seed--

--seed-contents--

py
def knight_moves(position):

    return position

--solutions--

py
def knight_moves(position):
    col = ord(position[0]) - ord('A')
    row = int(position[1]) - 1

    moves = [
        (2, 1), (2, -1),
        (-2, 1), (-2, -1),
        (1, 2), (1, -2),
        (-1, 2), (-1, -2)
    ]

    valid = 0

    for dx, dy in moves:
        new_col = col + dx
        new_row = row + dy

        if 0 <= new_col < 8 and 0 <= new_row < 8:
            valid += 1

    return valid