Open In App

Minimum Number of Bullets required to penetrate all bricks

Improve
Improve
Like Article
Like
Save
Share
Report

Given a matrix bricks[][] denoting the start and end coordinates of a brick’s breadth from an arrangement of rectangular bricks in a two-dimensional space. A bullet can be shot up exactly vertically from different points along the X-axis. A brick with coordinates Xstart and Xend is penetrated by the bullet which is shot from position X if Xstart ? X ? Xend. There is no limit on the number of bullets that can be shot and a bullet once shot keeps traveling along Y-axis infinitely. The task is to find the minimum number of bullets that must be shot to penetrate all the bricks.

Examples:

Input: bricks[][] = {{10, 16}, {2, 8}, {1, 6}, {7, 12}} 
Output:
Explanation: 
Shoot one bullet at X = 6, it penetrates the bricks places at {2, 8} and {1, 6} 
Another bullet at X = 11, it penetrates the bricks places at {7, 12} and {10, 16}

Input:bricks[][] = {{5000, 90000}, {150, 499}, {1, 100}} 
Output: 3

Approach: The idea is to use Greedy technique. Follow the steps below to solve this problem:

  1. Initialize the required count of bullets with 0.
  2. Sort the Xstart and Xend on the basis of Xend in ascending order.
  3. Iterate over the sorted list of positions and check if the Xstart of the current brick is greater than or equal to the Xend of the previous brick. If so, then one more bullet is required. So increment the count by 1. Otherwise proceed.
  4. Return the count at the end.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Custom comparator function
bool compare(vector<int>& a,
             vector<int>& b)
{
    return a[1] < b[1];
}
 
// Function to find the minimum number of
// bullets required to penetrate all bricks
int findMinBulletShots(vector<vector<int> >& points)
{
    // Sort the points in ascending order
    sort(points.begin(), points.end(),
         compare);
 
    // Check if there are no points
    if (points.size() == 0)
        return 0;
 
    int cnt = 1;
    int curr = points[0][1];
 
    // Iterate through all the points
    for (int j = 1; j < points.size(); j++) {
        if (curr < points[j][0]) {
 
            // Increase the count
            cnt++;
            curr = points[j][1];
        }
    }
 
    // Return the count
    return cnt;
}
 
// Driver Code
int main()
{
    // Given coordinates of bricks
    vector<vector<int> > bricks{ { 5000, 900000 },
                                 { 1, 100 },
                                 { 150, 499 } };
 
    // Function call
    cout << findMinBulletShots(bricks);
 
    return 0;
}


Java




// Java program for above approach
import java.util.*;
 
class GFG{
 
// Function to find the minimum number of
// bullets required to penetrate all bricks
static int findMinBulletShots(int[][] points)
{
     
    // Sort the points in ascending order
    Arrays.sort(points, (a, b) -> a[1] - b[1]);
     
    // Check if there are no points
    if (points.length == 0)
        return 0;
 
    int cnt = 1;
    int curr = points[0][1];
 
    // Iterate through all the points
    for(int j = 1; j < points.length; j++)
    {
        if (curr < points[j][0])
        {
             
            // Increase the count
            cnt++;
            curr = points[j][1];
        }
    }
 
    // Return the count
    return cnt;
}
 
// Driver code
public static void main (String[] args)
{
     
    // Given coordinates of bricks
    int[][] bricks = { { 5000, 900000 },
                       { 1, 100 },
                       { 150, 499 } };
     
    // Function call
    System.out.print(findMinBulletShots(bricks));
}
}
 
// This code is contributed by offbeat


Python3




# Python3 program for the above approach
 
# Function to find the minimum number of
# bullets required to penetrate all bricks
def findMinBulletShots(points):
 
    # Sort the points in ascending order
    for i in range(len(points)):
        points[i] = points[i][::-1]
 
    points = sorted(points)
 
    for i in range(len(points)):
        points[i] = points[i][::-1]
 
    # Check if there are no points
    if (len(points) == 0):
        return 0
 
    cnt = 1
    curr = points[0][1]
 
    # Iterate through all the points
    for j in range(1, len(points)):
        if (curr < points[j][0]):
 
            # Increase the count
            cnt += 1
            curr = points[j][1]
             
    # Return the count
    return cnt
 
# Driver Code
if __name__ == '__main__':
     
    # Given coordinates of bricks
    bricks = [ [ 5000, 900000 ],
               [ 1, 100 ],
               [ 150, 499 ] ]
 
    # Function call
    print(findMinBulletShots(bricks))
 
# This code is contributed by mohit kumar 29


Javascript




<script>
 
// JavaScript program for the above approach
 
// Custom comparator function
function compare(a,b)
{
    return a[1] - b[1];
}
 
// Function to find the minimum number of
// bullets required to penetrate all bricks
function findMinBulletShots(points)
{
 
    // Sort the points in ascending order
    points.sort(compare);
 
    // Check if there are no points
    if (points.length == 0)
        return 0;
 
    let cnt = 1;
    let curr = points[0][1];
 
    // Iterate through all the points
    for (let j = 1; j < points.length; j++) {
        if (curr < points[j][0]) {
 
            // Increase the count
            cnt++;
            curr = points[j][1];
        }
    }
 
    // Return the count
    return cnt;
}
 
// Driver Code
 
// Given coordinates of bricks
let bricks = [ [ 5000, 900000 ],
                                [ 1, 100 ],
                                [ 150, 499 ] ];
 
// Function call
document.write(findMinBulletShots(bricks),"</br>");
 
// This code is contributed by shinjanpatra
</script>


C#




using System;
using System.Collections.Generic;
 
public class PointComparer : IComparer<List<int>>
{
    public int Compare(List<int> a, List<int> b)
    {
        return a[1].CompareTo(b[1]);
    }
}
 
public class Program
{
    // Function to find the minimum number of
    // bullets required to penetrate all bricks
    public static int FindMinBulletShots(List<List<int>> points)
    {
        // Sort the points in ascending order
        points.Sort(new PointComparer());
 
        // Check if there are no points
        if (points.Count == 0)
            return 0;
 
        int cnt = 1;
        int curr = points[0][1];
 
        // Iterate through all the points
        for (int j = 1; j < points.Count; j++)
        {
            if (curr < points[j][0])
            {
                // Increase the count
                cnt++;
                curr = points[j][1];
            }
        }
 
        // Return the count
        return cnt;
    }
 
    // Driver Code
    public static void Main()
    {
        // Given coordinates of bricks
        List<List<int>> bricks = new List<List<int>>()
        {
            new List<int>(){ 5000, 900000 },
            new List<int>(){ 1, 100 },
            new List<int>(){ 150, 499 }
        };
 
        // Function call
        Console.WriteLine(FindMinBulletShots(bricks));
    }
}
 
// This code is contributed by Aditya Sharma


Output: 

3

Time Complexity: O(N * log N), where N is the number of bricks. 
Auxiliary Space: O(1)



Last Updated : 22 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads