写一个函数判断两个矩形是否相交,并尽量优化运行速度。
bool IsOverlapped(int x1,int y1,int w1,int h1,int x2,int y2,int w2,int h2)其中w 是矩形的宽度,h是矩形的高度

解决方案 »

  1.   

    import java.awt.Rectangle;
    public class RectIntersected { /**
     * @param args
     */
    public static void main(String[] args) {
    RectIntersected ri = new RectIntersected();
    Rectangle r1 = ri.getRect(5, 5, 5, 5);
    Rectangle r2 = ri.getRect(4, 5, 5, 5);
    System.out.println(ri.intersected(r1, r2)); }

    public boolean intersected(Rectangle r1,Rectangle r2) {
    if(r1.intersects(r2)) {
    return true;
    }
    return false;
    }


    public Rectangle getRect(int x, int y,int w,int h) {
    return new Rectangle(x,y,w,h);
    }}用AWT类的RECTANGLE类就可以
      

  2.   

    import java.awt.Rectangle;
    public class RectIntersected { /**
     * @param args
     */
    public static void main(String[] args) {
    RectIntersected ri = new RectIntersected();
    Rectangle r1 = new Rectangle(5,5,5,5);
    Rectangle r2 = new Rectangle(4,5,5,5);
    System.out.println(ri.intersected(r1, r2)); }

    public boolean intersected(Rectangle r1,Rectangle r2) {
    if(r1.intersects(r2)) {
    return true;
    }
    return false;
    }


    }