2012-11-06 69 views
-2

我已經實現了遞歸算法,可以在這個link下找到。 當3d數組爲10x10x10時,它工作得很好。如何強制Visual Studio忽略'System.StackOverflowException'?

我試圖讓它運行200x200x200數組,但是,Visual Studio說我可能會使用無限的資源(我很確定我的編程確定)。有什麼辦法來處理?我試圖在遞歸方法之前放[DebuggerNonUserCode],但它沒有奏效。

忘了提,這是Visual Studio 2010中

下面是我的程序遞歸函數。我爲每個細胞運行,標記爲Unvisited。

public static int tmp_lowest_floor = 0; 
    public static int tmp_maks_size = 0; 

    static void function1(Point[, ,] array, int pos_y, int pos_z, int pos_x) // recursive function 
    { 
     Point cell = array[pos_y, pos_z, pos_x]; 

     if (cell.Visited == false && cell.IsCave) 
     { 
      cell.Visited = true; // changing to visited so we do not count anything for this cell anymore 
      tmp_maks_size++; // increasing for each cell in this cave (in this run) 

      if (tmp_lowest_floor < pos_y) { tmp_lowest_floor = pos_y; } 
      cell.FillNeighbourList(array, pos_y, pos_z, pos_x);// adds neighbours into cell's list (max 6) up, down, north, east, south, west 

      foreach (Point p in cell.neighbours) // max 6 times recursion in here (I know it sounds horrible, but once I check all the neighbours for a cell, I'll not have to check it ever again) 
      { 
       if (p != null) 
       { 
        if (p.IsCave == true && p.Visited == false) 
        { 
         function1(tablica, p.pos_y, p.pos_z, p.pos_x); 
        } 
       } 
      } 

     } 

    } 

p.s. 我知道我可以用迭代的方式做,但是作業說它必須用遞歸來完成

+0

您不能忽略StackOverflowException。非遞歸地實現算法。 –

+1

StackOverflow是一個錯誤,而不是一個警告。你不能忽視。 – SLaks

+0

不僅你不能忽視這一點,現在你應該永遠。 – MyCodeSucks

回答

7

你不能忽視它,你真的會吹掉堆棧。

你所做的是要麼增加堆棧(從而延遲問題),要麼意識到手頭的問題是一個非常糟糕的算法實現,並修復它(例如,通過使用迭代方法或利用尾部 - 呼叫遞歸)。

另一方面,想知道您使用多少堆棧來遍歷200x200x200陣列中的每個單元格,只是跟蹤您的x,y和z座標系,而不是其他任何東西? 96MB。 Windows默認給你一個1MB寬的堆棧。

編輯:要解決您的具體問題,你有什麼是一個非常基本的填充算法。它的迭代形式使用隊列和列表。在僞代碼中:

list visited=[]; 
queue q=[]; 

q.push(startnode);   // the starting point 
while(!q.empty()) 
{ 
    // make sure we don't revisit nodes 
    if(visited.contains(node)) 
    continue; 

    visited.add(node=q.pop()); // we just visited the top 

    // do your conditions here, the cave thing? no clue what that is 
    // if it passes your filter, do any extra operations on your node here (none in your code) 

    // and push the neighbours in the queue 
    q.push_all(node.get_neighbours()); 
} 
+0

感謝使用迭代的代碼,不幸的是,我必須使用遞歸,這就是作業... – Patryk

4

運行時環境具有有限堆棧。每次調用方法時,都會有更多數據添加到該堆棧中。每次該方法返回時,都會從堆棧中刪除數據。如果你繼續在方法中調用方法,並且這些方法沒有返回,那麼你的堆棧最終會耗盡空間,並且你會得到堆棧溢出。

如果你想避免這種情況,你真的只需要修改你的算法使用較少的遞歸(調用方法中的方法),或滿足於使用足夠小的數據集,你的堆棧不會增長太大。

相關問題