给定一个矩形网格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
输出:
15
时间复杂度: O(1)
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。