Count tiles of dimensions 2 * 1 that can be placed in an M * N rectangular board that satisfies the given conditions
Last Updated :
22 Apr, 2021
Given two integers M and N, the task is to find the minimum number of tiles of size 2 * 1 that can be placed on an M * N grid such that the following conditions are satisfied:
- Each tile must completely cover 2 squares of the board.
- No pair of tiles may overlap.
- Each tile lies must be placed entirely inside the board. It is allowed to touch the edges of the board.
If it is not possible to cover the entire board, print -1
Input: N = 2, M = 4
Output: 4
Explanation: 4 tiles of dimension 2 * 1. Place each tile in one column.
Input: N = 3, M = 3
Output: -1
Approach: Follow the steps below to solve the problem
- If N is even, (N / 2) * M tiles can be placed to cover the entire board.
- If N is odd, tiles of 2 * 1 tiles, since the length is odd which can not be expressed as a multiple of 2
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int numberOfTiles( int N, int M)
{
if (N % 2 == 1) {
return -1;
}
return (N * 1LL * M) / 2;
}
int main()
{
int N = 2, M = 4;
cout << numberOfTiles(N, M);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int numberOfTiles( int n, int m)
{
if (n % 2 == 1 ) {
return - 1 ;
}
return (m * n) / 2 ;
}
public static void main(String[] args)
{
int n = 2 , m = 4 ;
System.out.println(
numberOfTiles(n, m));
}
}
|
Python
def numberOfTiles(N, M):
if (N % 2 = = 1 ):
return - 1
return (N * M) / / 2
N = 2
M = 4
print (numberOfTiles(N, M))
|
C#
using System;
public class GFG {
static int numberOfTiles( int n, int m)
{
if (n % 2 == 1) {
return -1;
}
return (m * n) / 2;
}
static public void Main()
{
int n = 2, m = 4;
Console.WriteLine(
numberOfTiles(n, m));
}
}
|
Javascript
<script>
function numberOfTiles(n, m)
{
if (n % 2 == 1)
{
return -1;
}
return (m * n) / 2;
}
var n = 2, m = 4;
document.write(numberOfTiles(n, m));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...