I solved this problem on Leetcode
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.
Input: [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]] Output: 2
Explanation:
The time complexity is O(height of the wall * total bricks in the wall)
assuming Add
, Remove
, ContainsKey
in Dictionary
is O(1)
and the space complexity is O(height of the wall)
.
I'm not sure if there is a better algorithm or more suited data structure that could improve the performance.
public int LeastBricksDictionary(IList<IList<int>> wall)
{
var totalRows = wall.Count;
var values = new SortedDictionary<int, List<Tuple<int, int>>>();
int leastBrick = int.MaxValue, bricksNotCrossing = 0;
for (int i = 0; i < wall.Count; i++)
{
var newTuple = new Tuple<int, int>(i, 0);
if (values.ContainsKey(wall[i][0]))
{
values[wall[i][0]].Add(newTuple);
}
else
{
values.Add(wall[i][0], new List<Tuple<int, int>>() { newTuple });
}
}
while (values.Count > 0)
{
int minSum = values.Keys.First();
var minList = values[minSum];
values.Remove(minSum);
bricksNotCrossing = 0;
foreach (var temp in minList)
{
int row = temp.Item1, col = temp.Item2;
if (wall[row].Count > 1 && col + 1 < wall[row].Count)
{
++bricksNotCrossing;
}
if (col + 1 < wall[row].Count)
{
int newSum = minSum + wall[row][col + 1];
var newTuple = new Tuple<int, int>(row, col + 1);
if (values.ContainsKey(newSum))
{
values[newSum].Add(newTuple);
}
else
{
values.Add(newSum, new List<Tuple<int, int>>() { newTuple });
}
}
}
leastBrick = Math.Min(leastBrick, totalRows - bricksNotCrossing);
}
return leastBrick;
}