×

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the primary job is to delete all portions of systems that are not visible after viewing them from a distance.

A triplet represents each building, and all structures have a standard bottom (left, ht, right)

  • Left: Is the left side of x coordinated(or wall)?
  • Right: The right side's x coordinate.
  • Ht: The building's height is indicated by ht.

An urban skyline is made up of many rectangular strips. A pair (left, ht) is used to describe a rectangular strip, where left denotes the x coordinate of the strip's left side and its height.

Example:

Buildings[][] = 1, 11, 5, 2, 6, 7, 9, 12, 14, 3, 25, 19, 18, 22, 23, 13, 29, 24, and 4 (in that order)

Output: 1, 11, 3, 13, 9, 0; 12, 7; 16, 3; 19, 18; 22, 3; 23, 13; 29, 0;

Approach:

  • Retrieve the left wall location, height, and correct wall location values for each structure from the triplets provided.
  • Keep the pair of the right wall's total height, and the left wall's negative height value in a vector called walls. This is done to distinguish between the left and right borders of the same building.
  • Order the walls from highest to lowest.
  • Cross the vector walls, and if a left wall is discovered, put its height in the multiset M. If a suitable barrier is met in any other case, take the multiset's appropriate height out.
  • Verify whether the top value has changed. Update the maximum value and save the current wall's abscissa if it has changed (x-coordinate).
  • The value pairs kept in the skyline vector should be printed.

Example:

// C++ programme for themethod described above
#include <bits/stdc++.h>
usingnamespace std;
// work to construct a skyline
vector<pair<int, int>>
create skylines(vector<vector<int>>& buildings)
{
 
    // learn how manybuildings there are.
    int N = buildings.size();
 
    // To keep track of the buildings' left and right wall positions.
    vector<pair<int, int>> wall;
 
    // triplet of architectural elements and parameters
    int left, height, right;
    for (inti = 0; i< N; i++) {
 
        // veer to the left of the building
        left = buildings[i][0];
 
        // veer to the left of the building
        height = buildings[i][1];
 
        // the appropriate building location
        right = buildings[i][2];
 
        // Keep left point and height in mind.
        // from the left wall.
        // Negative value indicates the left wall.
        // first be added into the multiset
        // identical abscissa(x) as the right wall
        wall.push_back({ left, -height });
 
        // Store the right wall's correct point and height.
        wall.push_back(
            make_pair(right, height));
    }
 
    // order the walls from highest to lowest
    sort(wall.begin(), wall.end());
 
    // output storing Skyline
    vector<pair<int, int>> skyline;
 
    // Begin a multiset with
    // Organize the heights of the left wall.
    multiset<int>leftWallHeight = { 0 };
 
    // Maximum height currently among leftWallHeights
    int top = 0;
 
    // Through the sorted walls, turn.
    For (autow wall) {
 
        // if one finds the left wall
        if (w.second< 0) {
 
            // Add the height.
            left all eight.insert(-w.second);
        }
 
        // if one finds the right wall
        else {
 
            // Take the height down
            left all eight.erase(
                left all eight.find(w.second));
        }
        //.rbegin(): Mark a skyline point if the top changes. backward iteration
 
        if (*leftWallHeight.rbegin() != top) {
 
            top = *leftWallHeight.rbegin();
            skyline.push_back(
                make_pair(w.first, top));
        }
    }
    //Skyline to print again Skyline
    return Skyline;
}
   // Print the output skyline using this function.
voidprint skyline(
    vector<vector<int>>& buildings)
{
 
      // Skyline creation function call
    vector<pair<int, int>> skyline
        = create skylines(buildings);
 
    cout<< "Skyline for the given."
         << " buildings:\n{";
 
    for (autoit: skyline) {
 
        cout<< "{" <<it.first<< ", "
             <<it.second<< "} ";
    }
    cout<< "}";
}
//Driver Number
 int main()
{
    vector<vector<int>> buildings;
    //Given the wall's height and the left and right locations,
    buildings = { { 1, 11, 5 }, { 2, 6, 7 },
                  { 3, 13, 9 }, { 12, 7, 16 },
                  { 14, 3, 25 }, { 19, 18, 22 },
                  { 23, 13, 29 }, { 24, 4, 28 } };
   //Feature Call
    print skyline(buildings);
    return 0;
}

Output:

Skyline Problem in C++

Time Complexity: O(n*log(N))

Auxiliary Space: O(N)


Related Topics

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples. Ternary Operator: The if-else statement and the conditional operator use...

3 minutes read.

Palindrome using For loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty...

3 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.