递归——谢尔宾斯基地毯/三角形、分段线
递归程序自己调用自己方法中调用自己本方法public void test(){ test(); }设计一个出口public void test(int n){ if(n50){ return; } n; test(n); }谢尔宾斯基地毯思路设置递归终止条件w5根据矩形大小设置矩形颜色填充当前矩形的中心区域把当前矩形平均分成9个小矩形填充正中间的那个递归绘制除去中心的8个小矩形重复执行拆分填充动作从左上、上中、右上再到左中、右中最后左下、下中、右下完成绘制public void drawSherBinRect(int x,int y,int w,int h){ if(w5){ return; } if(w300){ g.setColor(Color.BLUE); }else if(w50){ g.setColor(Color.YELLOW); }else{ g.setColor(Color.ORANGE); } g.fillRect(xw/3,yh/3,w/3,h/3); //递归调用 drawSherBinRect(x,y,w/3,h/3);//左上 drawSherBinRect(xw/3,y,w/3,h/3);//上中 drawSherBinRect(x2*w/3,y,w/3,h/3);//右上 drawSherBinRect(x,yh/3,w/3,h/3);//左中 drawSherBinRect(x2*w/3,yh/3,w/3,h/3);//右中 drawSherBinRect(x,y2*h/3,w/3,h/3);//左下 drawSherBinRect(xw/3,y2*h/3,w/3,h/3);//下中 drawSherBinRect(x2*w/3,y2*h/3,w/3,h/3);//右下 }谢尔宾斯基三角形思路设置递归终止条件n0计算三角形另外两个定点画出一个等边三角形取这个等边三角形每个边的中点连接画出中间三角形递归让上中下三个三角形重复此操作下图是n6时绘制出的图形public void drawSherBinTri(int x,int y,int sideLength,int n){ n--; if(n0){ return; } int x1x-sideLength/2; int y1y(int)(Math.sqrt(3)*sideLength/2); int x2xsideLength/2; int y2y1; g.drawLine(x,y,x1,y1); g.drawLine(x,y,x2,y2); g.drawLine(x1,y1,x2,y2); int x3(xx1)/2; int y3(yy1)/2; int x4(x1x2)/2; int y4(y1y2)/2; int x5(xx2)/2; int y5(yy2)/2; g.drawLine(x3,y3,x4,y4); g.drawLine(x5,y5,x4,y4); g.drawLine(x3,y3,x5,y5); drawSherBinTri(x3,y3,sideLength/2,n); drawSherBinTri(x5,y5,sideLength/2,n); drawSherBinTri(x,y,sideLength/2,n); }分段线思路画出一条水平直线将这条直线一分为二将最初的端点与分隔开的端点连接中间空出一段距离并将纵坐标下移一些下图是n6时绘制出的图形public void drawHalfLine(int x1,int x2,int y1,int n){ n--; if(n0){ return; } g.drawLine(x1,y1,x2,y1); int x3(x1x2)/2-5; int x4(x1x2)/25; int y3y15; g.drawLine(x1,y3,x3,y3); g.drawLine(x4,y3,x2,y3); drawHalfLine(x1,x3,y3,n); drawHalfLine(x4,x2,y3,n); }