📜  可以相交的最少砖块数

📅  最后修改于: 2021-10-26 06:55:25             🧑  作者: Mango

给定一个二维数组arr[][] ,表示墙上相同高度的砖块的宽度,任务是通过从顶部到底部绘制一条直线来找到可以相交的最小砖块数量墙。
注意:如果一条线穿过砖块,则称该线与砖块相交,如果它接触砖块的边界,则该线不相交。

例子:

朴素的方法:最简单的方法是考虑可以在x轴上的每个可能坐标上绘制的直线,沿着墙的宽度,在墙的左上角考虑 x = 0。然后,计算每种情况下插入的砖块数量并打印获得的最小数量。

时间复杂度: O(N * M) 其中N是砖的总数, M是墙的总宽度
辅助空间: O(1)

方法:优化上述方法,思路是将x轴上以一定宽度结束的砖块数量存储在一个hashmap中,然后找到砖块数量最多的那条线。得到这个计数后,从墙的总高度中减去它,得到最少的砖块数。

请按照以下步骤解决问题:

  • 初始化一个 hashmap, M来存储在 x 轴上以特定宽度结束的砖块的数量。
  • 遍历数组, arr使用变量i来存储行索引
    • 初始化一个变量, width0来存储结束位置。
    • 将当前行的大小存储在变量X 中
    • 使用变量j[0, X-2]范围内迭代
      • width的值增加arr[i][j]并将M 中width值增加1
      • 此外,跟踪以特定宽度结束的最多砖块数量,并将其存储在变量res 中
  • 从墙的总高度中减去res的值,并将其存储在变量ans 中
  • 打印ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find a line across a wall such
// that it intersects minimum number of bricks
void leastBricks(vector > wall)
{
    // Declare a hashmap
    unordered_map map;
 
    // Store the maximum number of
    // brick ending a point on x-axis
    int res = 0;
 
    // Iterate over all the rows
    for (vector list : wall) {
 
        // Initialize width as 0
        int width = 0;
 
        // Iterate over individual bricks
        for (int i = 0; i < list.size() - 1; i++) {
 
            // Add the width of the current
            // brick to the total width
            width += list[i];
 
            // Increment number of bricks
            // ending at this width position
            map[width]++;
 
            // Update the variable, res
            res = max(res, map[width]);
        }
    }
 
    // Print the answer
    cout << wall.size() - res;
}
 
// Driver Code
int main()
{
    // Given Input
    vector > arr{
        { 1, 2, 2, 1 }, { 3, 1, 2 },
        { 1, 3, 2 }, { 2, 4 },
        { 3, 1, 2 }, { 1, 3, 1, 1 }
    };
 
    // Function Call
    leastBricks(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
 
public class GFG
{
 
    // Function to find a line across a wall such
    // that it intersects minimum number of bricks
    static void leastBricks(ArrayList > wall)
    {
       
        // Declare a hashmap
        HashMap map = new HashMap<>();
 
        // Store the maximum number of
        // brick ending a point on x-axis
        int res = 0;
 
        // Iterate over all the rows
        for (ArrayList list : wall) {
 
            // Initialize width as 0
            int width = 0;
 
            // Iterate over individual bricks
            for (int i = 0; i < list.size() - 1; i++) {
 
                // Add the width of the current
                // brick to the total width
                width += list.get(i);
 
                // Increment number of bricks
                // ending at this width position
                map.put(width,
                        map.getOrDefault(width, 0) + 1);
 
                // Update the variable, res
                res = Math.max(res,
                               map.getOrDefault(width, 0));
            }
        }
 
        // Print the answer
        System.out.println(wall.size() - res);
    }
 
    // Driver code
    public static void main(String[] args)
    {
      // Given Input
        ArrayList > arr
            = new ArrayList<>();
        arr.add(new ArrayList<>(Arrays.asList(1, 2, 2, 1)));
        arr.add(new ArrayList<>(Arrays.asList(3, 1, 2)));
        arr.add(new ArrayList<>(Arrays.asList(1, 3, 2)));
        arr.add(new ArrayList<>(Arrays.asList(2, 4)));
        arr.add(new ArrayList<>(Arrays.asList(3, 1, 2)));
        arr.add(new ArrayList<>(Arrays.asList(1, 3, 1, 1)));
 
        // Function Call
        leastBricks(arr);
    }
}
 
// This code is contributed by abhinavjain194


Python3
# Python 3 program for the above approach
from collections import defaultdict
 
# Function to find a line across a wall such
# that it intersects minimum number of bricks
def leastBricks(wall):
 
    # Declare a hashmap
    map = defaultdict(int)
 
    # Store the maximum number of
    # brick ending a point on x-axis
    res = 0
 
    # Iterate over all the rows
    for list in wall:
 
        # Initialize width as 0
        width = 0
 
        # Iterate over individual bricks
        for i in range(len(list) - 1):
 
            # Add the width of the current
            # brick to the total width
            width += list[i]
 
            # Increment number of bricks
            # ending at this width position
            map[width] += 1
 
            # Update the variable, res
            res = max(res, map[width])
 
    # Print the answer
    print(len(wall) - res)
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given Input
    arr = [
        [1, 2, 2, 1], [3, 1, 2],
        [1, 3, 2], [2, 4],
        [3, 1, 2], [1, 3, 1, 1]
    ]
 
    # Function Call
    leastBricks(arr)
 
    # This code is contributed by ukasp.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to find a line across a wall such
// that it intersects minimum number of bricks
static void leastBricks(List> wall)
{
     
    // Declare a hashmap
    Dictionary map = new Dictionary();
 
    // Store the maximum number of
    // brick ending a point on x-axis
    int res = 0;
 
    // Iterate over all the rows
    foreach (List subList in wall)
    {
         
        // Initialize width as 0
        int width = 0;
        for(int i = 0; i < subList.Count - 1; i++)
        {
             
            // Add the width of the current
            // brick to the total width
            width += subList[i];
             
            // Increment number of bricks
            // ending at this width position
            if (map.ContainsKey(width))
                map[width]++;
            else
                map.Add(width, 1);
             
            // Update the variable, res
            res = Math.Max(res, map[width]);
        }
    }
 
    // Print the answer
    Console.Write(wall.Count-res);
}
 
// Driver Code
public static void Main()
{
     
    // Given Input
    List> myList = new List>();
    myList.Add(new List{ 1, 2, 2, 1 });
    myList.Add(new List{ 3, 1, 2 });
    myList.Add(new List{ 1, 3, 2 });
    myList.Add(new List{ 2, 4 });
    myList.Add(new List{ 3, 1, 2 });
    myList.Add(new List{ 1, 3, 1, 1 });
     
    // Function Call
    leastBricks(myList);
}
}
 
// This code is contributed by bgangwar59


Javascript


输出:
2

时间复杂度: O(N) 其中 N 是墙上的砖块总数
辅助空间: O(M) 其中 M 是墙的总宽度

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程