我需要完整代码,坐标用一个int类型的数组存储即可
时间: 2024-10-14 10:02:00 浏览: 15
理解了,如果你的坐标数据是整数数组的形式,我们可以稍微调整之前的代码来适应这种格式。首先,我们需要一个函数将坐标转换为`Rectangle`对象:
```python
def rect_from_coords(coords):
x1, y1, x2, y2 = coords
return Rectangle(x1, y1, x2, y2)
# 假设坐标数据是一个二维数组
coordinates_array = [[0, 2, 2, 0], [1, 1, 3, -1], [14, 14, 15, 13]]
rects = [rect_from_coords(coords) for coords in coordinates_array]
```
接下来,我们保持之前计算外周长的核心部分不变,只是修改一下创建矩形的部分。以下是完整的代码,包括计算外周长的功能:
```python
from collections import defaultdict
class Rectangle:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def intersects(self, other):
return not (other.x1 > self.x2 or other.x2 < self.x1 or other.y1 > self.y2 or other.y2 < self.y1)
def edge_intersection(self, edges, visited_edges):
intersection = 0
for edge in edges:
if edge[0] == edge[1]:
continue
intersection += min(edge[0].x2, edge[1].x2) - max(edge[0].x1, edge[1].x1)
intersection += min(edge[0].y2, edge[1].y2) - max(edge[0].y1, edge[1].y1)
visited_edges.add(edge)
return intersection
def get_perimeter(rectangles):
visited_edges = defaultdict(set) # 使用defaultdict简化处理无交叉情况
perimeter = 0
for r1 in rectangles:
for r2 in rectangles:
if r1 is not r2 and r1.intersects(r2):
new_edges = [(r1, r2), (r2, r1)]
perimeter += sum([abs(r1.x1 - r2.x1), abs(r1.y1 - r2.y1), abs(r1.x2 - r2.x2), abs(r1.y2 - r2.y2)])
intersection = r1.edge_intersection(new_edges, visited_edges[r1])
perimeter -= 2 * intersection # 减去两倍的重叠边
return perimeter
perimeter = get_perimeter(rects)
print("图形的外周长:", perimeter)
```
这段代码会计算所有相邻矩形组合的周长,然后减去它们之间的重叠部分。注意,这里我们使用`defaultdict`简化了处理不存在交叉情况,因为如果没有交叉,则不会添加新的边到`visited_edges`。
阅读全文