5

バックグラウンド:

私はアルゴリズムとJavaを学ぼうとしています。320x320のグリッドを実行すると、100回の試行が非再帰的なQuick-Union実装の約5倍の速度で実行されます。ただし、約400x400(160,000サイト)のグリッドを超えると、スタックオーバーフローエラーが発生します。

Javaが末尾再帰(非末尾再帰は言うまでもなく)用に最適化されていないことを理解しています。ただし、再帰的アルゴリズムは、より高速で安全に実行できるため、非再帰的バージョンよりも再帰的アルゴリズムを選択できる場合があると思います。

私はこのことを学んでいるだけであり、私のコードは最適ではない可能性があることを覚えておいてください。しかし、私は私の質問をよりよく理解するためにそれを含めています。

質問

再帰的アルゴリズムをJavaアプリケーションで安全に使用できる場合を評価するプロセスは何ですか(非再帰的アルゴリズムよりも高速に実行される場合)。

再帰的実装とUNION-FIND実装の統計

(注:2x比率は、単に前の現在の実行時間を前の実行時間で割ったものです)

|-----------|-----------|------------|-------------|-------------|
|     N     | Recursive | Recursive  | Quick-Union | Quick-Union |
|  (sites)  |    time   |  2x Ratio  |    time     |  2x Ratio   |
|===========|===========|============|=============|=============|
|     196   |      35   |            |      42     |             |
|     400   |      25   |    0.71    |      44     |     1.05    |
|     784   |      45   |    1.80    |      46     |     1.05    |
|    1600   |     107   |    2.38    |      86     |     1.87    |
|    3136   |      48   |    0.45    |     113     |     1.31    |
|    6400   |      75   |    1.56    |     303     |     2.68    |
|   12769   |     183   |    2.44    |     858     |     2.83    |
|   25600   |     479   |    2.62    |    2682     |     3.13    |
|   51076   |    1253   |    2.62    |    8521     |     3.18    |
|  102400   |    4730   |    3.77    |   27256     |     3.20    |
|-----------|-----------|------------|-------------|-------------|

再帰クラス

public class PercolateRecur implements Percolation {
  // the site has been opened for percolation but is not connected
  private final int OPEN = 0;
  // the site is not open for percolation (default state)
  private final int BLOCKED = -1;
  // the matrix that will be percolated. Values default to `BLOCKED = -1`
  // two sites that are connected together share the same value.
  private int[][] matrix;
  // the size of the sides of the matrix (1 to n)
  private int size;
  // whether water can flow from top to bottom of the matrix
  private boolean percolated;

  public PercolateRecur(int N) {
    percolated = false;
    size = N;
    initMatrix();
  }

  /**
   * initializes the matrix to default values
   */
  private void initMatrix() {
    matrix = new int[size+1][size+1];
    // open up the top of the matrix
    for (int x = 1; x < size+1; x++)
      matrix[x][0] = x;

    // set all values in matrix to closed
    for (int x = 1; x < size+1; x++)
      for (int y = 1; y < size+1; y++)
        matrix[x][y] = BLOCKED;
  }

  /**
   * indicates site (x,y) is a valid coordinate
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @return boolean
   */
  private boolean isValid(int x, int y) {
    return x > 0 && x < size+1 && y > 0 && y < size+1;
  }

  /**
   * returns value of site above (x,y)
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @return int value
   */
  private int above(int x, int y) {
    if (y <= 0)
      return BLOCKED;
    else
      return matrix[x][y-1];
  }

  /**
   * returns value of site below (x,y)
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @return int value
   */
  private int below(int x, int y) {
    if (y >= size)
      return BLOCKED;
    else
      return matrix[x][y+1];
  }

  /**
   * returns value of site left of (x,y)
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @return int value
   */
  private int left(int x, int y) {
    if (x <= 0)
      return BLOCKED;
    return matrix[x-1][y];
  }

  /**
   * returns value of site right of (x,y)
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @return int value
   */
  private int right(int x, int y) {
    if (x >= size)
      return BLOCKED;
    else
      return matrix[x+1][y];
  }

  /**
   * connects (x,y) to open adjacent sites
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   */
  private void connect(int x, int y) {
    if (isFull(x,y))
      return;
    if (above(x,y) > OPEN)
      matrix[x][y] = above(x, y);
    else if (below(x, y) > OPEN)
      matrix[x][y] = below(x, y);
    else if (left(x, y) > OPEN)
      matrix[x][y] = left(x, y);
    else if (right(x, y) > OPEN)
      matrix[x][y] = right(x, y);
    else if (matrix[x][y] == BLOCKED)
      matrix[x][y] = OPEN;
  }

  /**
   * recursively connects open sites in same group as (x,y)
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   */
  private void expand(int x, int y) {
    if (!isFull(x, y))
      return;
    if (above(x,y) == OPEN)
      openWith(x,y-1, matrix[x][y]);
    if (below(x,y) == OPEN)
      openWith(x,y+1, matrix[x][y]);
    if (left(x,y) == OPEN)
      openWith(x-1,y, matrix[x][y]);
    if (right(x,y) == OPEN)
      openWith(x+1,y, matrix[x][y]);
  }

  /**
   * opens a site (x,y) on the matrix
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   */
  public void open(int x, int y) {
    if (percolated || !isValid(x, y))
      return;
    connect(x, y);
    expand(x, y);
  }

  /**
   * opens a site with given value
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @param val value of point
   */
  private void openWith(int x, int y, int val) {
    matrix[x][y] = val;
    open(x, y);
  }

  /**
   * Returns whether site (x,y) is open
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @return true if not blocked
   */
    public boolean isOpen(int x, int y) {
    return matrix[x][y] > BLOCKED;
  }

  /**
   * Returns whether site (x,y) is full (connected to the top)
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @return true if is full
   */
  public boolean isFull(int x, int y) {
    return matrix[x][y] > OPEN;
  }

  /**
   * indicates whether site is blocked (not open)
   * @param x x-portion of x/y coordinate
   * @param y y-portion of x/y coordinate
   * @return true if blocked
   */
  public boolean isBlocked(int x, int y) {
    return matrix[x][y] == BLOCKED;
  }

  /**
   * indicates whether water can flow from top to bottom of matrix
   * @return true if matrix is percolated
   */
  public boolean percolates() {
    for (int x = 1; x <= size; x++)
      if (matrix[x][size] > OPEN)
        percolated = true;
    return percolated;
  }

  /**
   * prints the matrix to the command line
   */
  public void print() {
    for (int y = 1; y < size+1; y++) {
      System.out.println();
      for (int x = 1; x < size+1; x++) {
        if (matrix[x][y] == BLOCKED)
          System.out.print("XX ");
        else if (matrix[x][y] < 10)
          System.out.print(matrix[x][y] + "  ");
        else
          System.out.print(matrix[x][y] + " ");
      }
    }
    System.out.println();
  }
}
4

1 に答える 1

3

Javaで再帰的アルゴリズムを実装する際の問題の1つは、Javaプラットフォームが標準の「末尾呼び出しの除去」最適化を実行しないことです。これは、深い再帰には深いスタックが必要であることを意味します。また、Javaスレッドスタックは「成長」しないため、これはスタックオーバーフローに対して脆弱であることを意味します。

2つの回避策があります。

  • -Xssコマンドラインのオプションを使用するか、Threadコンストラクターで(より大きな)スタックサイズを明示的に指定することにより、スレッドスタックサイズを増やします。

  • Javaコードに末尾呼び出しの削除を明示的に実装します...控えめに言っても醜いです。

あなたの場合、最初の回避策は「真の再帰」の測定値を提供します。2番目の...まあ、アルゴリズムはもはや真に再帰的ではありませんが、それは「深い」問題のためにJavaで再帰的アルゴリズムを実用的にするためにあなたがするかもしれないことです。

注:Javaの再帰的アルゴリズムは、「シミュレートされたスタック」データ構造を使用して再帰状態を保持する同等の反復アルゴリズムにいつでも変換できます。アルゴリズムの複雑さは、両方のバージョンで同じである必要があります。おそらく、そのアプローチも試して、評価の3番目の列のペアとして「シミュレートされたスタック」バリアントを含める必要があります。

于 2013-02-17T05:34:27.533 に答える