# Count number of triangles cut by the given horizontal and vertical line segments

Given an array triangles[][] consisting of N triangles of the form {x1, y1, x2, y2, x3, y3} and an array cuts[] consisting of M horizontal and vertical lines of the form “X=x” or “Y=y” which represents the equation of the line segments. The task is to print the number of triangles intersected by each cut in such a way that the left and the right parts of the triangle should have areas greater than zero.

Examples:

Input: N = 2, triangles[][] = {{0, 2, 2, 9, 8, 5}, {5, 0, 6, 3, 7, 0}}, M = 3, cuts[] = {“X=2”, “Y=2”, “Y=9”}
Output: 1 1 0
Explanation:
The cut at X = 2 divides the first triangle having vertices (0, 2), (2, 9) and (8, 5)
The cut at Y = 2 divides the second triangle having vertices (5, 0), (6, 3) and  (7, 0)
The cut at Y = 9 divides none of the triangles.

Input: N = 2, triangles[][] = {{0, 2, 2, 9, 8, 5}}, M = 3, cuts[] = {“X=7”, “Y=7”, “X=9”}
Output: 1 1 0
Explanation:
The cut at X = 2 divides the first triangle having vertices (0, 2), (2, 9) and (8, 5)
The cut at Y = 2 divides the second triangle having vertices (5, 0), (6, 3) and (7, 0)
The cut at Y = 9 divides none of the triangles.

Approach: Below is the conditions for a line segment to divide a triangle into two parts having non-zero areas:

• If a cut is made at X-axis and it lies strictly in between the minimum and the maximum X coordinate of a triangle, then it divides the triangle in such a way that the left and the right parts should have areas greater than zero.
• Similarly, If a cut is made at Y-axis and it lies strictly in between the minimum and the maximum Y coordinate of a triangle, then it divides the triangle in such a way that the left and the right parts should have areas greater than zero.

Follow the steps below to solve the problem:

1. Create a structure to store the maximum and minimum X and Y coordinates for each triangle.
2. Traverse the array cuts[] array over the range [0, M – 1].
3. For each cut, initialize a counter count with 0 to store the answer for the current cut and start traversing the triangles[] array from j = 0 to N – 1.
4. Check for each triangle, cuts[i] is in the form X=x i.e., vertical cut and x strictly lies in between the maximum and the minimum X coordinate of ith triangle, increment the counter count otherwise continue checking other triangles for each cut.
5. After calculating the answer for cuts[i], print count.
6. Repeat the steps above for each cut and print the count of triangle cut by each line.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Store the minimum and maximum` `// X and Y coordinates` `struct` `Tri {` `    ``int` `MinX, MaxX, MinY, MaxY;` `};`   `// Function to convert string to int` `int` `StringtoInt(string s)` `{` `    ``stringstream geek(s);`   `    ``int` `x;` `    ``geek >> x;`   `    ``return` `x;` `}`   `// Function to print the number of` `// triangles cut by each line segment` `int` `TriangleCuts(` `    ``vector > Triangle,` `    ``string Cuts[], ``int` `N, ``int` `M, ``int` `COL)` `{`   `    ``// Initialize Structure` `    ``Tri Minimized[N];`   `    ``// Find maximum and minimum X and Y` `    ``// coordinates for each triangle` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``int` `x1 = Triangle[i][0];` `        ``int` `y1 = Triangle[i][1];` `        ``int` `x2 = Triangle[i][2];` `        ``int` `y2 = Triangle[i][3];` `        ``int` `x3 = Triangle[i][4];` `        ``int` `y3 = Triangle[i][5];`   `        ``// Minimum X` `        ``Minimized[i].MinX` `            ``= min({ x1, x2, x3 });`   `        ``// Maximum X` `        ``Minimized[i].MaxX` `            ``= max({ x1, x2, x3 });`   `        ``// Minimum Y` `        ``Minimized[i].MinY` `            ``= min({ y1, y2, y3 });`   `        ``// Maximum Y` `        ``Minimized[i].MaxY` `            ``= max({ y1, y2, y3 });` `    ``}`   `    ``// Traverse each cut from 0 to M-1` `    ``for` `(``int` `i = 0; i < M; i++) {`   `        ``string Cut = Cuts[i];`   `        ``// Store number of triangles cut` `        ``int` `CutCount = 0;`   `        ``// Extract value from the line` `        ``// segment string` `        ``int` `CutVal = StringtoInt(` `            ``Cut.substr(2, Cut.size()));`   `        ``// If cut is made on X-axis` `        ``if` `(Cut[0] == ``'X'``) {`   `            ``// Check for each triangle` `            ``// if x lies b/w max and` `            ``// min X coordinates` `            ``for` `(``int` `j = 0; j < N; j++) {`   `                ``if` `((Minimized[j].MinX)` `                        ``< (CutVal)` `                    ``&& (Minimized[j].MaxX)` `                           ``> (CutVal)) {` `                    ``CutCount++;` `                ``}` `            ``}` `        ``}`   `        ``// If cut is made on Y-axis` `        ``else` `if` `(Cut[0] == ``'Y'``) {`   `            ``// Check for each triangle` `            ``// if y lies b/w max and` `            ``// min Y coordinates` `            ``for` `(``int` `j = 0; j < N; j++) {` `                ``if` `((Minimized[j].MinY)` `                        ``< (CutVal)` `                    ``&& (Minimized[j].MaxY)` `                           ``> (CutVal)) {` `                    ``CutCount++;` `                ``}` `            ``}` `        ``}`   `        ``// Print answer for ith cut` `        ``cout << CutCount << ``" "``;` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given coordinates of triangles` `    ``vector > Triangle` `        ``= { { 0, 2, 2, 9, 8, 5 },` `            ``{ 5, 0, 6, 3, 7, 0 } };`   `    ``int` `N = Triangle.size();`   `    ``int` `COL = 6;`   `    ``// Given cuts of lines` `    ``string Cuts[] = { ``"X=2"``, ``"Y=2"``, ``"Y=9"` `};` `    ``int` `M = ``sizeof``(Cuts) / ``sizeof``(Cuts[0]);`   `    ``// Function Call` `    ``TriangleCuts(Triangle, Cuts,` `                 ``N, M, COL);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.util.*;`   `class` `GFG{`   `// Store the minimum and maximum` `// X and Y coordinates` `static` `class` `Tri` `{` `    ``int` `MinX, MaxX, MinY, MaxY;` `};`   `// Function to convert String to int` `static` `int` `StringtoInt(String s)` `{` `    ``return` `Integer.valueOf(s);` `}`   `static` `int` `min(``int` `a, ``int` `b, ``int` `c) ` `{` `    ``return` `Math.min(a, Math.min(b, c));` `}`   `static` `int` `max(``int` `a, ``int` `b, ``int` `c)` `{` `    ``return` `Math.max(a, Math.max(b, c));` `}`   `// Function to print the number of` `// triangles cut by each line segment` `static` `void` `TriangleCuts(``int``[][] Triangle,` `          ``String Cuts[], ``int` `N, ``int` `M, ``int` `COL)` `{` `    `  `    ``// Initialize Structure` `    ``Tri []Minimized = ``new` `Tri[N];` `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `        ``Minimized[i] = ``new` `Tri();` `        ``Minimized[i].MaxX = ``0``;` `        ``Minimized[i].MaxY = ``0``;` `        ``Minimized[i].MinX = ``0``;` `        ``Minimized[i].MinY = ``0``;` `    ``}`   `    ``// Find maximum and minimum X and Y` `    ``// coordinates for each triangle` `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `        ``int` `x1 = Triangle[i][``0``];` `        ``int` `y1 = Triangle[i][``1``];` `        ``int` `x2 = Triangle[i][``2``];` `        ``int` `y2 = Triangle[i][``3``];` `        ``int` `x3 = Triangle[i][``4``];` `        ``int` `y3 = Triangle[i][``5``];`   `        ``// Minimum X` `        ``Minimized[i].MinX = min(x1, x2, x3);`   `        ``// Maximum X` `        ``Minimized[i].MaxX = max(x1, x2, x3);`   `        ``// Minimum Y` `        ``Minimized[i].MinY = min(y1, y2, y3);`   `        ``// Maximum Y` `        ``Minimized[i].MaxY = max(y1, y2, y3);` `    ``}`   `    ``// Traverse each cut from 0 to M-1` `    ``for``(``int` `i = ``0``; i < M; i++)` `    ``{` `        ``String Cut = Cuts[i];` `        `  `        ``// Store number of triangles cut` `        ``int` `CutCount = ``0``;`   `        ``// Extract value from the line` `        ``// segment String` `        ``int` `CutVal = StringtoInt(` `            ``Cut.substring(``2``, Cut.length()));`   `        ``// If cut is made on X-axis` `        ``if` `(Cut.charAt(``0``) == ``'X'``)` `        ``{` `            `  `            ``// Check for each triangle` `            ``// if x lies b/w max and` `            ``// min X coordinates` `            ``for``(``int` `j = ``0``; j < N; j++)` `            ``{` `                `  `                ``if` `((Minimized[j].MinX) < (CutVal) && ` `                    ``(Minimized[j].MaxX) > (CutVal))` `                ``{` `                    ``CutCount++;` `                ``}` `            ``}` `        ``}`   `        ``// If cut is made on Y-axis` `        ``else` `if` `(Cut.charAt(``0``) == ``'Y'``)` `        ``{` `            `  `            ``// Check for each triangle` `            ``// if y lies b/w max and` `            ``// min Y coordinates` `            ``for``(``int` `j = ``0``; j < N; j++)` `            ``{` `                ``if` `((Minimized[j].MinY) < (CutVal) &&` `                    ``(Minimized[j].MaxY) > (CutVal)) ` `                ``{` `                    ``CutCount++;` `                ``}` `            ``}` `        ``}` `        `  `        ``// Print answer for ith cut` `        ``System.out.print(CutCount + ``" "``);` `    ``}` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `    `  `    ``// Given coordinates of triangles` `    ``int``[][] Triangle = { { ``0``, ``2``, ``2``, ``9``, ``8``, ``5` `},` `                         ``{ ``5``, ``0``, ``6``, ``3``, ``7``, ``0` `} };`   `    ``int` `N = Triangle.length;`   `    ``int` `COL = ``6``;`   `    ``// Given cuts of lines` `    ``String Cuts[] = { ``"X=2"``, ``"Y=2"``, ``"Y=9"` `};` `    ``int` `M = Cuts.length;`   `    ``// Function Call` `    ``TriangleCuts(Triangle, Cuts,` `                 ``N, M, COL);` `}` `}`   `// This code is contributed by Princi Singh`

## Python3

 `# Python program for the above approach`   `# Store the minimum and maximum` `# X and Y coordinates` `class` `Tri:` `    ``def` `__init__(``self``, MinX, MaxX, MinY, MaxY):` `        ``self``.MinX ``=` `MinX` `        ``self``.MaxX ``=` `MaxX` `        ``self``.MinY ``=` `MinY` `        ``self``.MaxY ``=` `MaxY`   `# Function to convert string to int` `def` `StringtoInt(s):` `    ``x ``=` `int``(s)` `    ``return` `x`   `# Function to print the number of` `# triangles cut by each line segment` `def` `TriangleCuts(Triangle, Cuts, N, M, COL):`   `    ``# Initialize Structure` `    ``Minimized ``=` `[]`   `    ``# Find maximum and minimum X and Y` `    ``# coordinates for each triangle` `    ``for` `i ``in` `range``(N):` `        ``x1 ``=` `Triangle[i][``0``]` `        ``y1 ``=` `Triangle[i][``1``]` `        ``x2 ``=` `Triangle[i][``2``]` `        ``y2 ``=` `Triangle[i][``3``]` `        ``x3 ``=` `Triangle[i][``4``]` `        ``y3 ``=` `Triangle[i][``5``]`   `        ``# Minimum X` `        ``MinX ``=` `min``(x1, x2, x3)`   `        ``# Maximum X` `        ``MaxX ``=` `max``(x1, x2, x3)`   `        ``# Minimum Y` `        ``MinY ``=` `min``(y1, y2, y3)`   `        ``# Maximum Y` `        ``MaxY ``=` `max``(y1, y2, y3)`   `        ``Minimized.append(Tri(MinX, MaxX, MinY, MaxY))`   `    ``# Traverse each cut from 0 to M-1` `    ``for` `i ``in` `range``(M):`   `        ``Cut ``=` `Cuts[i]`   `        ``# Store number of triangles cut` `        ``CutCount ``=` `0`   `        ``# Extract value from the line` `        ``# segment string` `        ``CutVal ``=` `StringtoInt(Cut[``2``:``len``(Cut)])`   `        ``# If cut is made on X-axis` `        ``if` `Cut[``0``] ``=``=` `'X'``:`   `            ``# Check for each triangle` `            ``# if x lies b/w max and` `            ``# min X coordinates` `            ``for` `j ``in` `range``(N):` `                ``if` `(Minimized[j].MinX) < (CutVal) ``and` `(Minimized[j].MaxX) > (CutVal):` `                    ``CutCount ``=` `CutCount ``+` `1`   `        ``# If cut is made on Y-axis` `        ``elif` `Cut[``0``] ``=``=` `'Y'``:`   `            ``# Check for each triangle` `            ``# if y lies b/w max and` `            ``# min Y coordinates` `            ``for` `j ``in` `range``(N):` `                ``if` `(Minimized[j].MinY) < (CutVal) ``and` `(Minimized[j].MaxY) > (CutVal):` `                    ``CutCount ``=` `CutCount ``+` `1`   `        ``# Print answer for ith cut` `        ``print``(CutCount,  end``=``' '``)`   `# Driver Code` `if` `__name__ ``=``=` `"__main__"``:` `  `  `    ``# Given coordinates of triangles` `    ``Triangle ``=` `[[``0``, ``2``, ``2``, ``9``, ``8``, ``5``], [``5``, ``0``, ``6``, ``3``, ``7``, ``0``]]`   `    ``N ``=` `len``(Triangle)`   `    ``COL ``=` `6`   `    ``# Given cuts of lines` `    ``Cuts ``=` `[``"X=2"``, ``"Y=2"``, ``"Y=9"``]` `    ``M ``=` `len``(Cuts)`   `    ``# Function Call` `    ``TriangleCuts(Triangle, Cuts, N, M, COL)`   `# The code is contributed by Gautam goel (gautamgoel962)`

## C#

 `// C# program for the above approach` `using` `System;`   `class` `GFG{`   `// Store the minimum and maximum` `// X and Y coordinates` `public` `class` `Tri` `{` `    ``public` `int` `MinX, MaxX, MinY, MaxY;` `};`   `// Function to convert String to int` `static` `int` `StringtoInt(String s)` `{` `    ``return` `Int32.Parse(s);` `}`   `static` `int` `min(``int` `a, ``int` `b, ``int` `c) ` `{` `    ``return` `Math.Min(a, Math.Min(b, c));` `}`   `static` `int` `max(``int` `a, ``int` `b, ``int` `c)` `{` `    ``return` `Math.Max(a, Math.Max(b, c));` `}`   `// Function to print the number of` `// triangles cut by each line segment` `static` `void` `TriangleCuts(``int``[,] Triangle,` `                         ``String []Cuts, ` `                         ``int` `N, ``int` `M, ` `                         ``int` `COL)` `{` `    `  `    ``// Initialize Structure` `    ``Tri []Minimized = ``new` `Tri[N];` `    ``for``(``int` `i = 0; i < N; i++)` `    ``{` `        ``Minimized[i] = ``new` `Tri();` `        ``Minimized[i].MaxX = 0;` `        ``Minimized[i].MaxY = 0;` `        ``Minimized[i].MinX = 0;` `        ``Minimized[i].MinY = 0;` `    ``}`   `    ``// Find maximum and minimum X and Y` `    ``// coordinates for each triangle` `    ``for``(``int` `i = 0; i < N; i++)` `    ``{` `        ``int` `x1 = Triangle[i, 0];` `        ``int` `y1 = Triangle[i, 1];` `        ``int` `x2 = Triangle[i, 2];` `        ``int` `y2 = Triangle[i, 3];` `        ``int` `x3 = Triangle[i, 4];` `        ``int` `y3 = Triangle[i, 5];`   `        ``// Minimum X` `        ``Minimized[i].MinX = min(x1, x2, x3);`   `        ``// Maximum X` `        ``Minimized[i].MaxX = max(x1, x2, x3);`   `        ``// Minimum Y` `        ``Minimized[i].MinY = min(y1, y2, y3);`   `        ``// Maximum Y` `        ``Minimized[i].MaxY = max(y1, y2, y3);` `    ``}`   `    ``// Traverse each cut from 0 to M-1` `    ``for``(``int` `i = 0; i < M; i++)` `    ``{` `        ``String Cut = Cuts[i];` `        `  `        ``// Store number of triangles cut` `        ``int` `CutCount = 0;`   `        ``// Extract value from the line` `        ``// segment String` `        ``int` `CutVal = StringtoInt(` `            ``Cut.Substring(2, Cut.Length - 2));`   `        ``// If cut is made on X-axis` `        ``if` `(Cut[0] == ``'X'``)` `        ``{` `            `  `            ``// Check for each triangle` `            ``// if x lies b/w max and` `            ``// min X coordinates` `            ``for``(``int` `j = 0; j < N; j++)` `            ``{` `                ``if` `((Minimized[j].MinX) < (CutVal) && ` `                    ``(Minimized[j].MaxX) > (CutVal))` `                ``{` `                    ``CutCount++;` `                ``}` `            ``}` `        ``}`   `        ``// If cut is made on Y-axis` `        ``else` `if` `(Cut[0] == ``'Y'``)` `        ``{` `            `  `            ``// Check for each triangle` `            ``// if y lies b/w max and` `            ``// min Y coordinates` `            ``for``(``int` `j = 0; j < N; j++)` `            ``{` `                ``if` `((Minimized[j].MinY) < (CutVal) &&` `                    ``(Minimized[j].MaxY) > (CutVal)) ` `                ``{` `                    ``CutCount++;` `                ``}` `            ``}` `        ``}` `        `  `        ``// Print answer for ith cut` `        ``Console.Write(CutCount + ``" "``);` `    ``}` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `    `  `    ``// Given coordinates of triangles` `    ``int``[,] Triangle = { { 0, 2, 2, 9, 8, 5 },` `                        ``{ 5, 0, 6, 3, 7, 0 } };`   `    ``int` `N = Triangle.GetLength(0);`   `    ``int` `COL = 6;`   `    ``// Given cuts of lines` `    ``String []Cuts = { ``"X=2"``, ``"Y=2"``, ``"Y=9"` `};` `    ``int` `M = Cuts.Length;`   `    ``// Function Call` `    ``TriangleCuts(Triangle, Cuts,` `                 ``N, M, COL);` `}` `}`   `// This code is contributed by Princi Singh`

## Javascript

 `// Javascript program for the above approach`   `    ``// Function to print the number of` `    ``// triangles cut by each line segment` `    ``function` `TriangleCuts(triangles, cuts) {` `    `  `    ``// Initialize Structure` `    ``let Minimized = ``new` `Array(triangles.length);` `     `  `    ``// Find maximum and minimum X and Y` `    ``// coordinates for each triangle` `    ``for` `(let i = 0; i < triangles.length; i++) {` `        ``let [x1, y1, x2, y2, x3, y3] = triangles[i];` `      `  `        ``Minimized[i] = {` `            ``// Minimum X` `            ``MinX: Math.min(x1, x2, x3),` `            ``// Maximum X` `            ``MaxX: Math.max(x1, x2, x3),` `            ``// Minimum Y` `            ``MinY: Math.min(y1, y2, y3),` `            ``// Maximum Y` `            ``MaxY: Math.max(y1, y2, y3)` `        ``}` `    ``}` `     `  `    ``// Traverse each cut from 0 to M-1` `    ``for` `(let i = 0; i < cuts.length; i++) ` `    ``{` `    `  `        ``// Store number of triangles cut` `        ``let CutCount = 0;` `        `  `        ``// Extract value from the line` `        ``// segment string` `        ``let CutVal = parseInt(cuts[i].substr(2));` `        `  `        ``// If cut is made on X-axis` `        ``if` `(cuts[i][0] === ``"X"``)` `        ``{` `        `  `            ``// Check for each triangle` `            ``// if x lies b/w max and` `            ``// min X coordinates` `            ``for` `(let j = 0; j < triangles.length; j++) {` `                ``if` `(Minimized[j].MinX < CutVal && Minimized[j].MaxX > CutVal) {` `                    ``CutCount++;` `                ``}` `            ``}` `        ``} ` `        ``// If cut is made on Y-axis` `        ``else` `if` `(cuts[i][0] === ``"Y"``) ` `        ``{` `        `  `            ``// Check for each triangle` `            ``// if y lies b/w max and` `            ``// min Y coordinates` `            ``for` `(let j = 0; j < triangles.length; j++) {` `                ``if` `(Minimized[j].MinY < CutVal && Minimized[j].MaxY > CutVal) {` `                    ``CutCount++;` `                ``}` `            ``}` `        ``}` `        ``// Print answer for ith cut` `        ``console.log(CutCount+``" "``);` `    ``}` `    ``}` `    `  `    `  `// Driver Code`   `    ``// Given coordinates of triangles` `    ``let triangles = [[0, 2, 2, 9, 8, 5], [5, 0, 6, 3, 7, 0]];` `    `  `    ``// Given cuts of lines` `    ``let cuts = [``"X=2"``, ``"Y=2"``, ``"Y=9"``];` `    `  `    ``// Function Call` `    ``TriangleCuts(triangles, cuts);` `   `

Output:

`1 1 0`

Time Complexity: O(M*N)
Auxiliary Space: O(M+N)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next