ch_hull.c
Upload User: gzelex
Upload Date: 2007-01-07
Package Size: 707k
Code Size: 2k
Development Platform:

MultiPlatform

  1. #include <LEDA/plane.h>
  2. #include <LEDA/window.h>
  3. window W;
  4. list<point> C_HULL(list<point> L)
  5.   if (L.length() < 3) return L;
  6.   list<point> CH;
  7.   list_item last;
  8.   point p;
  9.   L.sort();  // sort points lexicographically
  10.   // initialize convex hull with first two points
  11.   p = L.pop();
  12.   CH.append(p);
  13.   while (L.head() == p) L.pop();
  14.   last = CH.append(L.pop());
  15.   // scan remaining points
  16.   forall(p,L)
  17.   {
  18.     if (p == CH[last]) continue;  // multiple point
  19.     // compute upper tangent (p,high)
  20.     list_item high = last;
  21.     list_item it = CH.cyclic_pred(high);
  22.     while (left_turn(CH[it],CH[high],p))
  23.     { high = it;
  24.       it = CH.cyclic_pred(high);
  25.      }
  26.     // compute lower tangent (p,low)
  27.     list_item low = last;
  28.     it = CH.cyclic_succ(low);
  29.     while (right_turn(CH[it],CH[low],p))
  30.     { low = it;
  31.       it = CH.cyclic_succ(low);
  32.      }
  33.     // remove all points between high and low
  34.     if (high != low)
  35.     { it = CH.cyclic_succ(high);
  36.       while (it != low)
  37.       { CH.del(it);
  38.         it = CH.cyclic_succ(high);
  39.        }
  40.      }
  41.     // insert new point after "high"
  42.     last = CH.insert(p,high);
  43.    }
  44.   return CH;
  45. }
  46.      
  47. main()
  48. {
  49.   //window W;
  50.   W.init(-100,100,-100);
  51.   W.set_node_width(3);
  52.   int N = 500;
  53.   panel P("convex hull");
  54.   P.int_item("# points",N,1,2000);
  55.   int b1 = P.button("mouse");
  56.   int b2 = P.button("random");
  57.   int b3 = P.button("quit");
  58.   for(;;)
  59.   { 
  60.     list<point> L;
  61.     point p,q;
  62.     int but = P.open(0,0);
  63.     W.clear();
  64.     if (but == b1)
  65.       while (W >> p)
  66.       { W.draw_filled_node(p,blue2);
  67.         L.append(p);
  68.        }
  69.     if (but == b2)
  70.       for(int i = 0; i<N; i++) 
  71.       { point p(rand_int(-90,90),rand_int(-90,90));
  72.         W.draw_filled_node(p,blue2);
  73.         L.append(p);
  74.        }
  75.     if (but == b3) break;
  76.   
  77.     list<point> C = C_HULL(L);
  78.     W.set_mode(xor_mode);
  79.     W.draw_filled_polygon(C,yellow);
  80.     W.set_mode(src_mode);
  81.   
  82.   }
  83.    
  84.  return 0;
  85. }