2011-07-28 2 views
2

flood fill 알고리즘을 사용하여 목록에서 비슷한 인접 개체를 모두 찾아서 삭제하도록 표시하려고합니다. Wikipedia에서 의사 코드를 적용하려고 시도했지만 막히게되었습니다.홍수 채우기 알고리즘의 변형을 구현합니다.

목록의 각 객체에는 int X 값, int Y 값, Name 및 삭제 표시를위한 bool이 있습니다. 나는 그 이름에 매치하고 싶다.

프로그램이 try-catch없이 중단되고 프로그램이 종료됩니다. 오류 메시지를 리턴하지 않습니다. 여기 지금까지 제가 직접적으로 위에있는 객체를 찾으려고했습니다.

//Find neighbouring bubbles 
    gameGrid.DetectNeighbours2(gameGrid.planets.Last(), gameGrid.planets.Last().name); 


    //Flood fill algorithm to detect all connected planets 
     internal void DetectNeighbours(Planet p, Planet.Name planetName) 
     { 
      try 
      { 
       if (p.planet != planetName) 
        return; 

       p.deletable = true; 

       DetectNeighbours(GetTopNode(p), planetName); 
      } 

      catch (Exception err) 
      { 
       Debug.WriteLine(err.Message); 
      } 
     } 


     internal Planet GetTopNode(Planet b) 
     { 
      foreach (Planet gridPlanet in planets) 
      { 
       if (gridPlanet .Y == b.Y - 50) 
        return gridPlanet ;  
      } 

      return b; //Don't think this is right, but couldn't think of alternative 
     } 

답변

1

또는 이와 같이 다시 작성할 수 있습니다.

gameGrid.DetectNeighbours2(gameGrid.planets.Last()); 


//Flood fill algorithm to detect all connected planets 
    internal void DetectNeighbours(Planet p) 
    { 
     try 
     { 
      if (p == null || p.deletable) 
       return; 

      p.deletable = true; 

      DetectNeighbours(GetTopNode(p)); 
     } 

     catch (Exception err) 
     { 
      Debug.WriteLine(err.Message); 
     } 
    } 


    internal Planet GetTopNode(Planet b) 
    { 
     foreach (Planet gridPlanet in planets) 
     { 
      if (gridPlanet .Y == b.Y - 50) 
       return gridPlanet ;  
     } 

     return null; 
    } 
+0

필자는 그 비교'p.planet! = planetName'이 순전히 위에서 발견 된 행성이없는 경우를 감지하기 위해 추가되었다는 것을 알고 있습니까? 그런 다음이 대답은 올바른 방법 중 하나입니다. – unkulunkulu

+0

첫 번째 사례 이후에 추가 된 내용이 안전하다는 것이 맞습니다. – unkulunkulu

+0

감사합니다. 그렇게하는 것이 더 합리적이며 더 깨끗하게 보입니다. @David, 정확히 – David

1

첫째, 당신이이 문자열을 수정해야합니다

if (p.planet != planetName || p.deletable) 
    return; 

그래서 다시하고 다시 같은 지구를 방문하지 않습니다.

적어도 정지 (실제로는 무한 재귀)가 완화되어야합니다.

하지만 어쨌든이 알고리즘은 y 값을 줄이면 작동하지 않지만 모든 방향으로 이동하려고합니다.

+0

감사합니다.이 줄은 무한 재귀 문제를 해결했습니다. 먼저 다른 방향을 추가하기 전에 한 방향으로 작업하려고했습니다. 위의 내용이 여전히 삭제 될 것으로 예상했습니다. – David

+0

그것이 주된 문제였습니다. 나는 지금 내가 결승점에 올 수있을 것이라고 생각합니다. 다시 한 번 감사드립니다. – David

관련 문제