給定它們的中心和邊長,我們如何找到邊平行于x和y軸的n 個正方形的內部交集?
輸入是正方形的數量,然后是正方形的許多描述。每個正方形的描述是其中心和邊長的 x 和 y 坐標。例如:
3 5 11 10 7 9 10 10 6 8
描述了三個正方形,從一個以 (5, 11) 為中心,邊長為 10 的正方形開始。
uj5u.com熱心網友回復:
求由中心和長度給定的正方形(邊平行于x軸和y軸)內部交集的演算法是:
- 將第一個正方形的中心(點 ( x , y ))和長度 ( l ) 轉換為左邊緣 ( x ? l /2) 和右邊緣 ( x l /2 )的x坐標以及y底邊坐標 ( y ? l /2) 和頂邊坐標( y l /2)。將它們保留為left、right、bottom和top。
- 對于以下每個方格:
- 將其中心和長度轉換為上述坐標。
- 找出哪個x坐標更大,舊的left或新的左邊緣,并將其保留為新的left。
- 找出哪個x坐標較小,舊的right或新的 right 邊緣,并將其保留為新的right。
- 找出哪個y坐標更大,舊的底部或新的底部邊緣,并將其保留為新的底部。
- 找出哪個y坐標較小,舊頂部或新頂部邊緣,并將其保留為新頂部。
處理完所有正方形后,left、right、bottom和top是包圍所有正方形內區域的矩形的坐標。(如果right < left或top < bottom,則交點為空。否則,如果right = left或top = bottom,則交點是一條線 [如果只有一個是真的] 或一個點 [如果兩者都為真]。)
uj5u.com熱心網友回復:
這是一個計算兩個矩形之間交集的簡單函式。正方形是長方形,因此可以用于正方形。我假設矩形的高度和寬度平行于 y 和 x 軸。
struct point { double x, y; };
struct rectangle { struct point a, b; };
double max(double a, double b) { return a>b ? a : b; }
double min(double a, double b) { return a<b ? a : b; }
// Calculate the intersection of r1 and r2 and store the result in output
// Assumes that a.x < b.x and a.y < b.y for r1 and r2
// Returns NULL if there is no intersection
// Will always modify output. Do do NOT read output if this function returns NULL
struct rectangle *intersection(
struct rectangle *output,
const struct rectangle *r1,
const struct rectangle *r2)
{
output->a.x = max(r1->a.x, r2->a.x);
output->b.x = min(r1->b.x, r2->b.x);
if(output->a.x > output->b.x) return NULL;
output->a.y = max(r1->a.y, r2->a.y);
output->b.y = min(r1->b.y, r2->b.y);
if(output->a.y > output->b.y) return NULL;
return output;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379867.html
上一篇:在陣列中宣告結構型別的元素
下一篇:請更正我的代碼程式C語言
