Given a chess board  section of 5×5 size find the number of attacks can be done by knight, where 0 represents empty location and 1 represents occupied location by pawns. knight’s position is (2,2).

 

knight

The answer should be 3.

#include<stdio.h>
#include<stdbool.h>

#define ROW 8
#define COL 8
bool chess[][COL] = {
  {0, 1, 0, 1, 0}
  ,
  {1, 0, 1, 0, 1}
  ,
  {0, 0, 1, 1, 0}
  ,
  {1, 0, 0, 0, 1}
  ,
  {1, 1, 0, 0, 0}
};

// knight position (2,2)

int findAttcks (bool chess[][COL], int x, int y);
bool canGoEast (int x, int y);
bool canGoWest (int x, int y);
bool canGoNorth (int x, int y);
bool canGoSouth (int x, int y);

int
main ()
{
  // knight's position
  int x = 2;
  int y = 2;
  // number of attacks
  printf ("%d \n", findAttcks (chess, x, y));
  return 0;
}

int
findAttcks (bool chess[][COL], int x, int y)
{
  int c = 0;
  //check can go to east
  if (canGoEast (x, y))
    {
      if (chess[x - 1][y + 2] && (x - 1 >= 0))
    c++;
      if (chess[x + 1][y + 2] && (x + 1 < ROW))
    c++;
    }

  //check can go to west
  if (canGoWest (x, y))
    {
      if (chess[x + 1][y - 2] && (x + 1 < ROW))
    c++;
      if (chess[x - 1][y - 2] && (x - 1 >= 0))
    c++;
    }
  //check can go to north
  if (canGoNorth (x, y))
    {
      if (chess[x - 2][y - 1] && (y - 1 >= 0))
    c++;
      if (chess[x - 2][y + 1] && (y + 1 < COL))
    c++;
    }
  //check can go to south
  if (canGoSouth (x, y))
    {
      if (chess[x + 2][y - 1] && (y - 1 >= 0))
    c++;
      if (chess[x + 2][y + 1] && (y + 1 < ROW))
    c++;
    }
  return c;
}

bool
canGoEast (int x, int y)
{

  if (x >= 0 && (y + 1 < COL) && (y + 2 < COL))
    {
      if (!chess[x][y + 1] && !chess[x][y + 2])
    return true;
      else
    return false;
    }
  return false;
}

bool
canGoWest (int x, int y)
{
  if (x >= 0 && (y - 1 < COL && (y - 1) >= 0)
      && ((y - 2 >= 0) && (y - 2 < COL)))
    {
      if (!chess[x][y - 1] && !chess[x][y - 2])
    return true;
      else
    return false;
    }
  return false;
}

bool
canGoNorth (int x, int y)
{
  if ((x - 1) >= 0 && (x - 2) >= 0 && x >= 0 && y >= 0)
    {
      if (!chess[x - 1][y] && !chess[x - 2])
    return true;
      else
    return false;
    }
  return false;
}

bool
canGoSouth (int x, int y)
{
  if ((x + 1 < ROW && (x + 2 < ROW) && y > 0 && x >= 0))
    {
      if (!chess[x + 1][y] && !chess[x + 2][y])
    return true;
      else
    return false;
    }
}



Related Contents to follow