📌  相关文章
📜  最初放置在给定 NxM 棋盘左上角的主教可到达的方格数

📅  最后修改于: 2022-05-13 01:56:08.992000             🧑  作者: Mango

最初放置在给定 NxM 棋盘左上角的主教可到达的方格数

给定两个整数NM代表N x M棋盘,任务是找到主教在最初放置在棋盘的左上角时使用任意数量的移动可以达到的最大方格数。

例子:

方法:给定的问题可以通过观察从(1, 1)到达的瓦片的数量是与 (1, 1 ) 相同颜色的瓦片来解决。此类瓷砖的数量可以通过公式ceil((N*M)/2)计算。上述陈述被证明是错误的情况是N = 1M = 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)