首页 > 解决方案 > 递归不打印错误但卡住了

问题描述

我的代码似乎卡在第一次递归中。我的 IDE 也不会打印出任何 StackOverflow 错误或其他错误。

该算法的目的是找到图像的所有彩色区域。

任何有关解决此问题的帮助将不胜感激。

PS:pixels[] 是任何“PImage”的 rgb 值数组。

public class Test {

  PImage finalImage;

  public Test(PImage pImage) {
    finalImage = pImage.get(0, 0, pImage.width, pImage.height);
  }

  public void floodFill() {
    int targetColor;
    for (int x = 0; x < finalImage.width; x+=3) {
      for (int y = 0; y < finalImage.height; y+=3) {
        targetColor = finalImage.pixels[index(x, y, finalImage)];
        flood4(x, y, targetColor, color(69, 69, 69));
      }
    }
  }

  public void flood4(int x, int y, int target, int replacement) {

    finalImage.loadPixels();

    int currentColor = finalImage.pixels[index(x, y, finalImage)];

    if (currentColor != target) {
      return;
    }

    if (currentColor == replacement) {
      return;
    }

    if (!inBounds(x, y, finalImage)) {
      return;
    }

    finalImage.pixels[index(x, y, finalImage)] = replacement;

    finalImage.updatePixels();

    flood4(x+1, y, target, replacement);
    flood4(x-1, y, target, replacement);
    flood4(x, y+1, target, replacement);
    flood4(x, y-1, target, replacement);
  }

  PImage getImage() {
    return finalImage.get(0, 0, finalImage.width, finalImage.height);
  }
}

boolean inBounds(int x, int y, PImage img) {
  return x>-1&&x<img.width&&y>-1&&y<img.height;
}

标签: javaalgorithmrecursion

解决方案


推荐阅读