Count of squares reachable by a Bishop initially placed at top left on a given NxM chessboard
Last Updated :
29 Nov, 2021
Given two integers N and M representing a N x M chessboard, the task is to find the maximum number of squares that the bishop can reach using any number of moves if initially it is placed in the top left corner of the chessboard.
Examples:
Input: N = 8, M = 8
Output: 32
Explanation: The bishop is initially standing on (1, 1) which is either a white or a black colour tile. Therefore, either all the black or the white tiles can be visited from (1, 1) using a sequence of moves depending on the color of the (1, 1) tile.
Input: N = 7, M = 3
Output: 11
Approach: The given problem can be solved by observing the fact that the number of reachable tiles from (1, 1) are the tiles with the same color as that of (1, 1). The count of such tiles can be calculated by the formula ceil((N*M)/2). The case where the above-mentioned statement proves wrong is the case where either N = 1 or M = 1. In such cases, no cells are reachable from (1, 1) and hence the required answer is 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maximumSquares( int N, int M)
{
if (N == 1 || M == 1) {
return 1;
}
return (N * M + 1) / 2;
}
int main()
{
int N = 7;
int M = 3;
cout << maximumSquares(N, M);
return 0;
}
|
Java
class GFG {
static int maximumSquares( int N, int M)
{
if (N == 1 || M == 1 ) {
return 1 ;
}
return (N * M + 1 ) / 2 ;
}
public static void main (String[] args) {
int N = 7 ;
int M = 3 ;
System.out.println(maximumSquares(N, M));
}
}
|
Python
def maximumSquares(N, M) :
if (N = = 1 or M = = 1 ) :
return 1
return (N * M + 1 ) / / 2
if __name__ = = "__main__" :
N = 7
M = 3
print (maximumSquares(N, M))
|
C#
using System;
class GFG {
static int maximumSquares( int N, int M)
{
if (N == 1 || M == 1) {
return 1;
}
return (N * M + 1) / 2;
}
public static void Main () {
int N = 7;
int M = 3;
Console.Write(maximumSquares(N, M));
}
}
|
Javascript
<script>
function maximumSquares(N, M)
{
if (N == 1 || M == 1) {
return 1;
}
return (N * M + 1) / 2;
}
let N = 7;
let M = 3;
document.write(maximumSquares(N, M));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...