2011-04-16 23 views
0

我有n列,n行的每一個元素被初始化爲0。圈的選擇 - Java的

我想選擇該矩陣的最大圓,並設置一個矩陣值爲1.

000010000 
000111000 
000111000 
001111100 
011111110  The drawing isnt't very artistic (or correct)... 
001111100  matrix: 9*9 
000111000  largest circle 
000111000 
000010000 

你能幫我用java算法嗎?

語言:Java的

謝謝 霍拉丘

+0

我只是想知道,這功課? – 2011-04-16 13:27:17

+0

看起來像一個菱形 – jberg 2011-04-16 13:31:39

+0

這傢伙是要求人們給他一個算法?我勒個去??? – 2011-04-16 13:33:22

回答

3

這裏有一個天真的算法。它將每個點填充到0或1,具體取決於它是位於圓內還是外。

public static void main(String[] args) 
{ 
    int[][] matrix = new int[9][]; 
    double midPoint = (matrix.length-1)/2.0; 
    for (int col = 0; col < matrix.length; col++) 
    { 
     int[] row = new int[matrix.length]; 
     double yy = col-midPoint; 
     for (int x=0; x<row.length; x++) 
     { 
      double xx = x-midPoint; 
      if (Math.sqrt(xx*xx+yy*yy)<=midPoint) 
      row[x] = 1; 
      System.out.print(row[x]); 
     } 
     matrix[col] = row; 
     System.out.println(); 
    } 

} 
+0

謝謝,它工作得很好 – 2011-04-16 13:58:19

4

最有效的方法找了一圈邊界的正確像素是Bresenhamn的算法或者中間點圓算法; http://en.wikipedia.org/wiki/Midpoint_circle_algorithm#Optimization

這是我如何改變這種狀況,以適應你的:

public class Circle { 
    private char[][] px; 
    private char cEmpty='.'; 
    private char cFilled='#'; 
    public static void main(String[] args) { 
     new Circle(15); 
    } 
    public Circle(int size) 
    { 
     px=new char[size][size]; 
     for(int i=0;i<size;i++) 
      for(int j=0;j<size;j++) 
       px[i][j]=cEmpty; 
     calc(size/2,size/2,size/2-1); 
     for(int i=0;i<size;i++){ 
      for(int j=0;j<size;j++) 
       System.out.print(px[i][j]); 
      System.out.println(); 
     } 
    } 

    public void calc(int cx, int cy, int radius) 
    { 
     int error = -radius; 
     int x = radius; 
     int y = 0; 
     while (x >= y) 
     { 
     plot8points(cx, cy, x, y); 
     error += y; 
     ++y; 
     error += y; 
     if (error >= 0) 
     { 
      --x; 
      error -= x; 
      error -= x; 
     } 
     } 
    } 

    void plot8points(int cx, int cy, int x, int y) 
    { 
     plot4points(cx, cy, x, y); 
     if (x != y) plot4points(cx, cy, y, x); 
    } 
    void plot4points(int cx, int cy, int x, int y) 
    { 
     setPixel(cx + x, cy + y); 
     if (x != 0) setPixel(cx - x, cy + y); 
     if (y != 0) setPixel(cx + x, cy - y); 
     if (x != 0 && y != 0) setPixel(cx - x, cy - y); 
    } 
    void setPixel(int x, int y){ 
     px[x][y]=cFilled; 
    } 
} 
+0

謝謝你的時間。但是我選擇了mdma的實現,因爲他的圈子被填滿了。 – 2011-04-16 13:57:50