[LeetCode] Brick Wall

554. Brick Wall

There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.

Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.

  • hash table solution
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int leastBricks(vector<vector<int>>& wall) {
unordered_map<int, int> freq;
int n = wall.size(), res = n;
for(auto& row : wall) {
for(int i = 0, psum = 0; i < row.size() - 1; i ++) {
res = min(res, n - ++freq[psum += row[i]]);
}
}
return res;
}
};
  • heap solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
int leastBricks(vector<vector<int>>& A) {
priority_queue<pair<int, int>,vector<pair<int, int>>,greater<pair<int, int>>> q;
priority_queue<int, vector<int>, greater<int>> fin;
int res = A.size(), inc = 0, now = 0, sum = 0;
for(auto& row : A) {
int psum = 0;
for(auto& col : row) {
q.push({psum,psum+col});
psum += col;
}
sum = psum;
}
while(!q.empty()) {
int mi = q.top().first;
now = mi;
if(!fin.empty()) mi = min(mi, fin.top());
while(!fin.empty() and fin.top() == mi) {
inc--;
fin.pop();
}
if(now != 0 and now != sum) res = min(res, inc);
while(!q.empty() and q.top().first == mi) {
fin.push(q.top().second); q.pop();
inc++;
}
}
while(!fin.empty()) {
int f = fin.top();
now = f;
while(!fin.empty() and fin.top() == f) {
inc--;
fin.pop();
}
if(now != 0 and now != sum) res = min(res,inc);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/13/PS/LeetCode/brick-wall/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.