2013
11-09

# Intersection

You are to write a program that has to decide whether a given line segment intersects a given rectangle.

An example:

line: start point: (4,9)

end point: (11,2)

rectangle: left-top: (1,5)

right-bottom: (7,1)

Figure 1: Line segment does not intersect rectangle

The line is said to intersect the rectangle if the line and the rectangle have at least one point in common. The rectangle consists of four straight lines and the area in between. Although all input values are integer numbers, valid intersection points do not have to lay on the integer grid.

The input consists of n test cases. The first line of the input file contains the number n. Each following line contains one test case of the format:

xstart ystart xend yend xleft ytop xright ybottom

where (xstart, ystart) is the start and (xend, yend) the end point of the line and (xleft, ytop) the top left and (xright, ybottom) the bottom right corner of the rectangle. The eight numbers are separated by a blank. The terms top left and bottom right do not imply any ordering of coordinates.

For each test case in the input file, the output file should contain a line consisting either of the letter “T” if the line segment intersects the rectangle or the letter “F” if the line segment does not intersect the rectangle.

1
4 9 11 2 1 5 7 1

F

//* @author popop0p0popo
import java.util.*;
import java.io.*;

public class Main{
public static void main(String[] args){
int n=scanner.nextInt();
double dx1,dx2,dy1,dy2;
double x1,x2,y1,y2;
double k,b;
double d1,d2,d3,d4;
for (int i=0;i n ;i++ ){
x1=scanner.nextDouble();
y1=scanner.nextDouble();
x2=scanner.nextDouble();
y2=scanner.nextDouble();
dx1=scanner.nextDouble();
dy1=scanner.nextDouble();
dx2=scanner.nextDouble();
dy2=scanner.nextDouble();
if (dx1>dx2){
double tx=dx1;
dx1=dx2;
dx2=tx;
}
if (dy1>dy2){
double ty=dy1;
dy1=dy2;
dy2=ty;
}
if ((x1< dx1&&x2< dx1)||(x1>dx2&&x2>dx2)){
System.out.println("F");
}
else if ((y1< dy1&&y2< dy1)||(y1>dy2&&y2>dy2)){
System.out.println("F");
}
else{
if (x1==x2){
System.out.println("T");
}
else{
k=(y2-y1)/(x2-x1);
b=y1-k*x1;
d1=dy1-k*dx1-b;
d2=dy2-k*dx2-b;
d3=dy1-k*dx2-b;
d4=dy2-k*dx1-b;
if ((d1>0&&d2>0&&d3>0&&d4>0)||(d1<0&&d2<0&&d3<0&&d4<0)){
System.out.println("F");
}
else{
System.out.println("T");
}
}
}
}
}
}

1. 这道题目虽然简单，但是小编做的很到位，应该会给很多人启发吧！对于面试当中不给开辟额外空间的问题不是绝对的，实际上至少是允许少数变量存在的。之前遇到相似的问题也是恍然大悟，今天看到小编这篇文章相见恨晚。