LeetCode:Brick Wall

554. Brick Wall

There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.

The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

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.

Example:

Input: 
[[1,2,2,1],
 [3,1,2],
 [1,3,2],
 [2,4],
 [3,1,2],
 [1,3,1,1]]
Output: 2
Explanation: 
思路:很有意思的一个题目,这里使用关键在于最优划线是传过尽量多的缝隙,从这个角度出发只要记录下每个数组的数组和,找到相同的和取最大值就可以了。
 
 1 int leastBricks(vector<vector<int>>& wall)
 2 {
 3     map<int, int>m;
 4     int r = 0;
 5     int size = wall.size();
 6 
 7     for (int i = 0; i < size; i++)
 8     {
 9         int len = wall[i].size();
10         int b = wall[i][0];
11         ++m[b];
12         r = max(r, m[b]);
13         for (int j = 1; j < len - 1; j++)
14         {
15             b += wall[i][j];
16             ++m[b];
17             r = max(r, m[b]);
18         }
19     }
20     if (m.size() == 1)
21         return size;
22     return r == 1 ? size - 1 : size - r;
23 }

 

如果你有任何疑问或新的思路,欢迎在下方评论。

posted @ 2017-04-12 13:48  陆小风不写代码  阅读(216)  评论(0编辑  收藏  举报