我希望用户在谷歌地图上绘制一个多边形形状 - 这不是一个问题,并将其排序。 当用户然后单击一个按钮时,我需要确定特定大小的矩形形状将适合该多边形。
我遇到的问题是如果多边形是例如6m x 4m并且需要适合的形状是2m x 3m,那么你只能容纳3个形状(如果形状是并排的,则总面积为6m x 3m)留下6m x 1m的面积。
剩余区域与形状相同,但尺寸错误。
我如何看待有多少"整体"形状适合多边形?
答案 0 :(得分:4)
这实际上是一个难题,packing problems一个完整解决方案的特定情况会变得相当复杂,可能是NP难的。
导出次优解决方案应该相当容易。我们可以考虑两种可能的解决方案,矩形水平或垂直,它们在一个统一的网格中。
让大矩形的大小为A
X B
,小矩形为a
X b
。对于未旋转的版本,我们可以水平放置m=floor(A/a)
,垂直放置n=floor(B/b)
,总共放入n*m
个项目。旋转90º,我们有p=floor(A/b)
和q=floor(B/a)
共有p*q
项。
上面会有一些没有给出最佳解决方案,比如将2X3矩形拟合到5×4中。如果两个是水平的,一个是垂直的,那么你可以装入3个。
对于不规则的多边形边界,您可以将它们排成行,每行之间的距离等于较小矩形的高度。
伪代码解决方案可能类似于
poly = getPolygon() // get the input polygon
a = rectangle.height // size of rectangle we are trying to fit
b = rectangle.width // size of rectangle
row_height = 10
bounds = poly.getBoundingBox()
offset_top = a/2 // y coord of the first row
// loop from top to bottom
for(y = bounds.top + offset_top ; y < bounds.bottom; y += a )
{
// find all the solutions of the polygon with a horizontal line
sols1 = poly.intersectWithHorizontalLine(y)
// find sols of bottom line
sols2 = poly.intersectWithHorizontalLine(y+a)
// find the left most and right most points
left = min(sols1,sols2)
right = max(sols1,sols2)
// now can draw the rectangles
for(x=left; x < right; x += b)
{
drawRectangle( x , y, width=b, height=a)
}
}