给定一个NxM尺寸的矩形网格,任务是找到将给定的矩形网格分成大小为1×1的正方形所需的最小切割次数。
例子:
Input: N = 4, M = 4
Output: 15
Input: N = 2, M = 1
Output: 1
方法:
上图显示了矩形网格的分裂。我们可以观察到,每一次切割都会将不同维度的矩形数量增加1 。我们将进行分裂,直到我们达到维度1×1的平方。
因此,对于给定的 NxM 矩形尺寸,1×1 尺寸的正方形总数为 N*M。因此,我们需要N*M – 1次切割才能将 NxM 的给定矩形尺寸分解为尺寸为 1×1 的正方形。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
// Function to find the minimum cuts
void minimumCuts(int N, int M)
{
// Print the minimum cuts using
// the formula
cout << (N * M - 1);
}
// Driver Code
int main()
{
// Given dimensions
int N = 4, M = 4;
// Function call
minimumCuts(N, M);
return 0;
}
Java
// Java program of the above approach
import java.util.*;
class GFG{
// Function to find the minimum cuts
static void minimumCuts(int N, int M)
{
// Print the minimum cuts using
// the formula
System.out.print(N * M - 1);
}
// Driver Code
public static void main(String[] args)
{
// Given dimensions
int N = 4, M = 4;
// Function call
minimumCuts(N, M);
}
}
// This code is contributed by Rohit_ranjan
Python3
# Python3 program of the above approach
# Function to find the minimum cuts
def minimumCuts(N, M):
# Print the minimum cuts using
# the formula
print(N * M - 1)
# Driver Code
if __name__ == "__main__":
# Given dimensions
N = 4
M = 4
# Function call
minimumCuts(N, M)
# This code is contributed by coder001
C#
// C# program of the above approach
using System;
class GFG{
// Function to find the minimum cuts
static void minimumCuts(int N, int M)
{
// Print the minimum cuts using
// the formula
Console.Write(N * M - 1);
}
// Driver Code
public static void Main(String[] args)
{
// Given dimensions
int N = 4, M = 4;
// Function call
minimumCuts(N, M);
}
}
// This code is contributed by Princi Singh
Javascript
输出:
15
时间复杂度: O(1)