Given the position of the king on an 8 X 8 chessboard, the task is to count the total number of squares that can be visited by the king in m moves. The position of the king is denoted using row and column number.
Note: The square which is currently acquired by the king is already visited and will be counted in the result.
Examples:
Input: r = 4, c = 4, m = 1
Output: 9
Input: r = 4, c = 4, m = 2
Output: 25
Approach: A king can move one square in any direction (i.e horizontally, vertically and diagonally). So, in one move king can visit its adjacent squares.

So, A square which is within m units distance (Considering 1 Square as 1 unit distance) from the king’s current position can be visited in m moves.
For all squares of the chessboard, check if a particular square is at m unit distance away or less from King’s current position.
- Increment count, if step 1 is true.
- Print the count
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSquares( int r, int c, int m)
{
int squares = 0;
for ( int i = 1; i <= 8; i++) {
for ( int j = 1; j <= 8; j++) {
if (max( abs (i - r), abs (j - c)) <= m)
squares++;
}
}
return squares;
}
int main()
{
int r = 4, c = 4, m = 1;
cout << countSquares(r, c, m) << endl;
return 0;
}
|
Java
class GFG {
static int countSquares( int r, int c, int m)
{
int squares = 0 ;
for ( int i = 1 ; i <= 8 ; i++) {
for ( int j = 1 ; j <= 8 ; j++) {
if (Math.max(Math.abs(i - r), Math.abs(j - c)) <= m)
squares++;
}
}
return squares;
}
public static void main(String[] args)
{
int r = 4 , c = 4 , m = 1 ;
System.out.print(countSquares(r, c, m));
}
}
|
C#
using System;
class GFG {
static int countSquares( int r, int c, int m)
{
int squares = 0;
for ( int i = 1; i <= 8; i++) {
for ( int j = 1; j <= 8; j++) {
if (Math.Max(Math.Abs(i - r), Math.Abs(j - c)) <= m)
squares++;
}
}
return squares;
}
public static void Main()
{
int r = 4, c = 4, m = 1;
Console.Write(countSquares(r, c, m));
}
}
|
Python3
def countSquares(r, c, m):
squares = 0
for i in range ( 1 , 9 ):
for j in range ( 1 , 9 ):
if ( max ( abs (i - r), abs (j - c)) < = m):
squares = squares + 1
return squares
r = 4
c = 4
m = 1
print (countSquares(r, c, m));
|
PHP
<?php
function countSquares( $r , $c , $m )
{
$squares = 0;
for ( $i = 1; $i <= 8; $i ++)
{
for ( $j = 1; $j <= 8; $j ++)
{
if (max( abs ( $i - $r ),
abs ( $j - $c )) <= $m )
$squares ++;
}
}
return $squares ;
}
$r = 4;
$c = 4;
$m = 1;
echo countSquares( $r , $c , $m );
?>
|
Javascript
<script>
function countSquares(r, c, m)
{
let squares = 0;
for (let i = 1; i <= 8; i++) {
for (let j = 1; j <= 8; j++) {
if (Math.max(Math.abs(i - r), Math.abs(j - c)) <= m)
squares++;
}
}
return squares;
}
let r = 4, c = 4, m = 1;
document.write(countSquares(r, c, m));
</script>
|
Time Complexity: O(1), since the loop runs for a total of 64 times, that is constant time only.
Auxiliary Space: O(1), since no extra space has been taken.