最初放置在给定 NxM 棋盘左上角的主教可到达的方格数
给定两个整数N和M代表N x M棋盘,任务是找到主教在最初放置在棋盘的左上角时使用任意数量的移动可以达到的最大方格数。
例子:
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
方法:给定的问题可以通过观察从(1, 1)到达的瓦片的数量是与 (1, 1 ) 相同颜色的瓦片来解决。此类瓷砖的数量可以通过公式ceil((N*M)/2)计算。上述陈述被证明是错误的情况是N = 1或M = 1的情况。在这种情况下,从(1, 1)无法到达任何单元格,因此所需的答案是1 。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
// Function to find the maximum number of
// reachable squares by a bishop in an
// N x M chessboard
int maximumSquares(int N, int M)
{
// If either of N or M is equal to 1
if (N == 1 || M == 1) {
return 1;
}
// Otherwise the required
// answer is Ceil(N*M/2)
// Return Answer
return (N * M + 1) / 2;
}
// Driver Code
int main()
{
int N = 7;
int M = 3;
cout << maximumSquares(N, M);
return 0;
}
Java
// Java program for the above approach
class GFG {
// Function to find the maximum number of
// reachable squares by a bishop in an
// N x M chessboard
static int maximumSquares(int N, int M)
{
// If either of N or M is equal to 1
if (N == 1 || M == 1) {
return 1;
}
// Otherwise the required
// answer is Ceil(N*M/2)
// Return Answer
return (N * M + 1) / 2;
}
// Driver Code
public static void main (String[] args) {
int N = 7;
int M = 3;
System.out.println(maximumSquares(N, M));
}
}
// This code is contributed by target_2.
Python
# Python program of the above approach
# Function to find the maximum number of
# reachable squares by a bishop in an
# N x M chessboard
def maximumSquares(N, M) :
# If either of N or M is equal to 1
if (N == 1 or M == 1) :
return 1
# Otherwise the required
# answer is Ceil(N*M/2)
# Return Answer
return (N * M + 1) // 2
# Driver Code
if __name__ == "__main__" :
N = 7
M = 3
print(maximumSquares(N, M))
# This code is contributed by Samim Hossain Mondal.
C#
// C# program for the above approach
using System;
class GFG {
// Function to find the maximum number of
// reachable squares by a bishop in an
// N x M chessboard
static int maximumSquares(int N, int M)
{
// If either of N or M is equal to 1
if (N == 1 || M == 1) {
return 1;
}
// Otherwise the required
// answer is Ceil(N*M/2)
// Return Answer
return (N * M + 1) / 2;
}
// Driver Code
public static void Main () {
int N = 7;
int M = 3;
Console.Write(maximumSquares(N, M));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
11
时间复杂度: O(1)
辅助空间: O(1)