  
高级难度  
深度优先算法 
 
 
代码如下: 
			
			
			- void setup() {
 -   size(300, 300);
 -   background(55);
 -   noStroke();
 -   fill(255);
 -  
 -   int n=12, n2=n*2; 
 -   float w=width/float(n2+1);
 -   int[][] map=new int[n2][n2];
 -  
 -   int x=0, y=0;
 -   ArrayList<Point> points = new ArrayList<Point>();
 -   points.add(new Point(0, 0));
 -   ArrayList<ComplexPoint> complexPoints = new ArrayList<ComplexPoint>();
 -  
 -   for (int j=0; j<n2; j++) {
 -     for (int i=0; i<n2; i++) {
 -       if (i%2==0 && j%2==0) {
 -         map[j][i]=1;
 -       }
 -     }
 -   }
 -  
 -   while (!points.isEmpty ()) {
 -     int count=0;
 -     if (x-2>0 && map[y][x-2]==1) {
 -       complexPoints.add(new ComplexPoint(x-2, y, x-1, y));
 -       count++;
 -     }
 -     if (x+2<n2 && map[y][x+2]==1) {
 -       complexPoints.add(new ComplexPoint(x+2, y, x+1, y));
 -       count++;
 -     }
 -     if (y-2>0 && map[y-2][x]==1) {
 -       complexPoints.add(new ComplexPoint(x, y-2, x, y-1));
 -       count++;
 -     }
 -     if (y+2<n2 && map[y+2][x]==1) {
 -       complexPoints.add(new ComplexPoint(x, y+2, x, y+1));
 -       count++;
 -     }
 -  
 -     if (count>0) {
 -       points.add(new Point(x, y));
 -       ComplexPoint complexPoint = complexPoints.get(int(random(count)));
 -       map[complexPoint.y][complexPoint.x] = 2;
 -       map[complexPoint.py][complexPoint.px] = 2;
 -       x = complexPoint.x;
 -       y = complexPoint.y;
 -       complexPoints.clear();
 -     } else {
 -       Point point = points.get(points.size()-1);
 -       x = point.x;
 -       y = point.y;
 -       points.remove(points.size()-1);
 -     }
 -   }
 -  
 -   rect(0, 0, width, w);
 -   rect(0, 0, w, height);
 -   for (int j=0; j<n2; j++) {
 -     for (int i=0; i<n2; i++) {
 -       if (map[j][i]==0) {
 -         rect(w*(i+1), w*(j+1), w, w);
 -       }
 -     }
 -   }
 - }
 -  
 - class Point {
 -   int x, y;
 -   Point(int x, int y) {
 -     this.x=x;
 -     this.y=y;
 -   }
 - }
 -  
 - class ComplexPoint {
 -   int x, y, px, py;
 -   ComplexPoint(int x, int y, int px, int py) {
 -     this.x=x;
 -     this.y=y;
 -     this.px=px;
 -     this.py=py;
 -   }
 - }
 
  复制代码
  
 
 
 
授权转载自 任远媒体实验室 
 |