package aiqyInterview;
public class CheckIntersect {
*
* @author EdwardZhang
* 判断线段相交:
* 两个线段的交点个数可能有0个 1个或者无数个
* 判断两个线段相交,可以按照如下步骤:
* 判断A点B点是否在线段CD的两侧,即计算叉积时异号
* 判断C点和D点是否在线段AB的两侧,即计算叉积时异号
* 然后在处理特殊情况,即ABCD四个点有至少三个点共线的情况,
* 即出现叉积为零的情况,如果A点与线段CD共线,
* 则要查看A点是否在线段CD上,其它情况依次类推。
*/
class Point {
int x;
int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
class Line {
Point A = new Point();
Point B = new Point();
public Point getA() {
return A;
}
public void setA(int i, int j) {
A.x = i;
A.y = j;
}
public Point getB() {
return B;
}
public void setB(int i, int j) {
B.x = i;
B.y = j;
}
}
public static float direct(Point i, Point j, Point k) {
return (k.x - i.x) * (j.y - i.y) - (j.x - i.x) * (k.y - i.y);
}
public static boolean onSegment(Point a, Point b, Point c) {
float minx = Math.min(a.x, b.x);
float maxx = Math.max(a.x, b.x);
float miny = Math.min(a.y, b.y);
float maxy = Math.max(a.y, b.y);
if (c.x >= minx && c.x <= maxx && c.y >= miny && c.y <= maxy) {
return true;
}
return false;
}
public static boolean checkIntersect(Line X, Line Y) {
float d1 = direct(Y.A, Y.B, X.A);
float d2 = direct(Y.A, Y.B, X.B);
float d3 = direct(X.A, X.B, Y.A);
float d4 = direct(X.A, X.B, Y.B);
if (d1 * d2 < 0 && d3 * d4 < 0)
return true;
else if (d1 == 0 && onSegment(Y.A, Y.B, X.A))
return true;
else if (d2 == 0 && onSegment(Y.A, Y.B, X.B))
return true;
else if (d3 == 0 && onSegment(X.A, X.B, Y.A))
return true;
else if (d4 == 0 && onSegment(X.A, X.B, Y.B))
return true;
return false;
}
public static void main(String[] args) {
CheckIntersect checkIntersect = new CheckIntersect();
Line a = checkIntersect.new Line();
Line b = checkIntersect.new Line();
a.setA(0, 0);
a.setB(2, 2);
b.setA(2, 0);
b.setB(0, 2);
System.out.println(checkIntersect(a,b));
a.setA(0, 0);
a.setB(2, 2);
b.setA(2, 0);
b.setB(1, 0);
System.out.println(checkIntersect(a,b));
a.setA(0, 0);
a.setB(2, 2);
b.setA(2, 0);
b.setB(4, 2);
System.out.println(checkIntersect(a,b));
a.setA(0, 0);
a.setB(2, 2);
b.setA(1, 1);
b.setB(3, 3);
System.out.println(checkIntersect(a,b));
}
}