Knight Attacks – Solution in C

Area: two-dimensional arrays – matrices

The program reads the position of a knight on a chessboard (row m and column n, both from 1 to 8) and prints the board: the knight's square is marked with 0, every square the knight attacks is marked with its chess name (e.g. c4), and all other squares with *.

#include <stdio.h>
#include <string.h>

int main() {
    // Read the knight's position (row and column)
    int m, n;
    scanf("%d %d", &m, &n);

    // The board as a matrix of strings; all strings start empty
    char board[9][9][3] = {{{0}}};

    // Fill the board from row 8 down to row 1
    for (int i = 8; i >= 1; i--) {
        for (int j = 1; j <= 8; j++) {
            if (i == m && j == n) { // the current square is the knight's
                int v = 0; // helper variable for shifting the columns
                for (int r = i + 2; r >= i - 2; r--) {
                    if (r > i) v++;            // shift the column to the right
                    else if (r < i - 1) v--;   // shift the column to the left
                    else if (r == i) continue; // the knight's own row has no attacked squares
                    // Skip rows outside the board
                    if (r < 1 || r > 8) continue;
                    // Columns of the attacked squares on the right and on the left
                    int col1 = n + v; // right
                    int col2 = n - v; // left

                    // Build the square names (e.g. "c4")
                    char right[3] = {(char)('a' + col1 - 1), (char)('0' + r), '\0'};
                    char left[3] = {(char)('a' + col2 - 1), (char)('0' + r), '\0'};

                    // Put the attacked squares on the board
                    if (col1 <= 8) strcpy(board[r][col1], right);
                    if (col2 >= 1) strcpy(board[r][col2], left);
                }
                // Mark the knight's square with " 0"
                strcpy(board[i][j], " 0");
            } else {
                if (strlen(board[i][j]) == 0) {
                    // Fill the remaining squares with " *"
                    strcpy(board[i][j], " *");
                }
            }
        }
    }

    // Print the board
    for (int i = 8; i >= 1; i--) {
        for (int j = 1; j <= 8; j++) {
            printf("%s ", board[i][j]);
        }
        printf("\n");
    }

    return 0;
}

For example, for the input 4 3 the program prints:

 *  *  *  *  *  *  *  *
 *  *  *  *  *  *  *  *
 * b6  * d6  *  *  *  *
a5  *  *  * e5  *  *  *
 *  *  0  *  *  *  *  *
a3  *  *  * e3  *  *  *
 * b2  * d2  *  *  *  *
 *  *  *  *  *  *  *  * 

Key parts of the code and explanation

Initializing the board:

char board[9][9][3] = {{{0}}};

A two-dimensional array of strings of size 9x9 is created to represent the chessboard. Although the board is 8x8, a 9x9 matrix is used for easier indexing (the indices go from 1 to 8, which matches chess notation). Every string has room for two characters and the terminating '\0', and all of them start empty.

The loop that fills the board:

for (int i = 8; i >= 1; i--)
{
    for (int j = 1; j <= 8; j++)
    {

This loop goes through all squares of the chessboard, starting from row 8 (the top row in the printout) down to row 1, and from the left to the right column (j=1 to j=8).

Finding the knight's position:

if (i == m && j == n)

When the knight's position (m, n) is reached, the program starts marking the squares the knight attacks.

Marking the squares the knight attacks:

for (int r = i + 2; r >= i - 2; r--)

This loop goes through all rows the knight can attack (two rows above and two rows below the knight). The variable v holds the column shift, which depends on the current row (1 for rows that are two away, 2 for rows that are one away).

  • col1 and col2 are the columns the knight attacks.
  • 'a' + col − 1 is the letter of that column (a–h).
  • '0' + r is the row the knight attacks (1–8).
  • right and left are the names of the squares the knight attacks.

Marking the knight's position:

strcpy(board[i][j], " 0");

The square where the knight stands gets " 0" to show that this is the knight's position.

Filling the remaining squares:

if (strlen(board[i][j]) == 0)
{
    strcpy(board[i][j], " *");
}

All other squares that are not attacked and do not hold the knight are filled with asterisks (*). Squares in the rows above the knight were already filled with " *" before the knight was reached, but strcpy overwrites them with the names of the attacked squares.

Printing the board:

for (int i = 8; i >= 1; i--)
{
    for (int j = 1; j <= 8; j++)
    {
        printf("%s ", board[i][j]); // print every element of the board
    }
    printf("\n"); // a new line for the next row
}

Finally the board is printed so that every line is one row of the chessboard.

Result: the output is a chessboard with the names of the squares the knight attacks, the knight's position marked with " 0", and all other squares filled with asterisks.

This program shows the basic principles of working with two-dimensional arrays, handling strings and basic algorithmic ideas in C.

Analysis of how optimal the code is

  • Extra iterations:
    • The code checks the area of 5 rows around the knight and computes the columns from the row distance, which is harder to follow than listing the moves directly. A knight can attack only eight specific squares (if they are inside the board).
  • Redundant placing of asterisks:
    • The code places asterisks and attack marks in the same pass, so some squares are written twice. This could be simplified by first filling the whole board with asterisks and then marking only the attacked squares.

Optimized code

#include <stdio.h>
#include <string.h>

int main() {
    // Read the knight's position (row and column)
    int m, n;
    scanf("%d %d", &m, &n);

    // A matrix of strings that represents the chessboard
    char board[9][9][3];

    // All possible knight moves
    int dx[] = {2, 2, 1, 1, -2, -2, -1, -1};
    int dy[] = {1, -1, 2, -2, 1, -1, 2, -2};

    // Fill the board with the starting values
    for (int i = 8; i >= 1; --i) {
        for (int j = 1; j <= 8; ++j) {
            if (i == m && j == n) {
                // The knight's current position is marked with "0"
                strcpy(board[i][j], " 0");
            } else {
                // We assume that all other squares are not attacked
                strcpy(board[i][j], " *");
            }
        }
    }

    // Check the squares the knight can attack
    for (int k = 0; k < 8; ++k) {
        // New coordinates of the knight's move
        int ni = m + dx[k];
        int nj = n + dy[k];
        if (ni >= 1 && ni <= 8 && nj >= 1 && nj <= 8) {
            // Convert the coordinates to chess notation (e.g. c4)
            board[ni][nj][0] = 'a' + nj - 1; // column letter
            board[ni][nj][1] = '0' + ni;     // row number
            board[ni][nj][2] = '\0';
        }
    }

    // Print the chessboard
    for (int i = 8; i >= 1; --i) {
        for (int j = 1; j <= 8; ++j) {
            printf("%s ", board[i][j]);
        }
        printf("\n");
    }

    return 0;
}

For the same input 4 3 the optimized program prints the same board as the first one.

Improvements in the optimized code

  • Clarity and simplicity: all possible knight moves are clearly defined in two arrays (dx and dy). These arrays make it easy to go through all squares the knight can attack.
  • Efficiency: the code now uses only one loop of 8 steps for the attacked squares, instead of going through rows and computing columns.
  • Correctness: the code also checks whether the attacked squares are inside the board, so it never writes names to squares that do not exist.

Code optimized like this is easier to understand, faster to run and more efficient in terms of memory and processor time.