- 将所有计算过中点的边存入hashmap中
- 后续的每条边计算中点先到hashmap当中查询是否存-在存在就不用计算了 直接获取之前算过的中点
- 边类:两个端点 中点
- 重写equals方法用两个端点做比较不论方向- hashcode方法也要重写 计算hash值根据端点计算
- K-V边 对象-K 中点-V
packagelbx628;importjavax.swing.*;importjava.awt.*;importjava.util.HashMap;importjava.util.Objects;importjava.util.Random;publicclassDrawmidextendsJFrame{// 边类:两个端点,用于HashMap的KeypublicclassEdge{Pointp1,p2;//构造publicEdge(Pointp1,Pointp2){this.p1=p1;this.p2=p2;}publicbooleanequals(Objecto){//判断地址是否相同,如果地址相同的话,那就相同//this表示调动equals方法的对象if(this==o){returntrue;}// getClass()获取一个类的字节码对象,注:同一个类的字节码对象是相等的// ||有true则true,具备短路作用,左边为true右边不执行// o == null,对象为null,提高代码的健壮性if(o==null||/*省略了this.*/getClass()!=o.getClass()){returnfalse;}// 强制类型转换,o 强制转换成 e,目的是为了调用子类特有的成员//e:oEdgee=(Edge)o;return(p1.equals(e.p1)&&p2.equals(e.p2))||(p1.equals(e.p2)&&p2.equals(e.p1));}publicinthashCode(){Pointa,b;if(p1.x<p2.x||(p1.x==p2.x&&p1.y<p2.y)){a=p1;b=p2;}else{a=p2;b=p1;}returnObjects.hash(a,b);}}Randomrandom=newRandom();HashMap<Edge,Point>hm=newHashMap<>();// 边→中点 缓存publicDrawmid(){setTitle("谢尔宾斯基三角形递归");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(800,800);setLocationRelativeTo(null);setVisible(true);}@Overridepublicvoidpaint(Graphicsg){super.paint(g);drawmidRect(g,400,50,150,650,700,650,100,150);}publicPointgetMid(intx1,inty1,intx2,inty2){Edgee=newEdge(newPoint(x1,y1),newPoint(x2,y2));Pointp=hm.get(e);if(p!=null){returnp;}p=newPoint((x1+x2)/2,(y1+y2)/2);hm.put(e,p);returnp;}publicvoiddrawmidRect(Graphicsg,intx1,inty1,intx2,inty2,intx3,inty3,intrx,intry){if(Math.abs(x3-x2)<80||Math.abs(y3-y1)<80){g.drawLine(x1,y1,x2,y2);g.drawLine(x1,y1,x3,y3);g.drawLine(x2,y2,x3,y3);return;}Pointpm1=getMid(x1,y1,x2,y2);Pointpm2=getMid(x2,y2,x3,y3);Pointpm3=getMid(x1,y1,x3,y3);if(rx>0&&ry>0){pm1.x+=random.nextInt(rx*2)-rx;pm1.y+=random.nextInt(ry*2)-ry;pm2.x+=random.nextInt(rx*2)-rx;pm2.y+=random.nextInt(ry*2)-ry;pm3.x+=random.nextInt(rx*2)-rx;pm3.y+=random.nextInt(ry*2)-ry;}intnr=Math.max(1,rx/2);intny=Math.max(1,ry/2);drawmidRect(g,x1,y1,pm1.x,pm1.y,pm3.x,pm3.y,nr,ny);drawmidRect(g,pm1.x,pm1.y,x2,y2,pm2.x,pm2.y,nr,ny);drawmidRect(g,pm3.x,pm3.y,pm2.x,pm2.y,x3,y3,nr,ny);drawmidRect(g,pm1.x,pm1.y,pm2.x,pm2.y,pm3.x,pm3.y,nr,ny);}publicstaticvoidmain(String[]args){newDrawmid();}}