【问题标题】:Queue and While loop memory exception队列和 While 循环内存异常
【发布时间】:2014-10-28 18:25:58
【问题描述】:

我似乎无法理解为什么这会引发内存异常。在对“安全”相邻单元进行排队时,出现内存异常。任何想法是为什么以及会导致这种情况的原因是什么?

for (int x = 0; x < 10; x++) {
    for (int y = 0; y < 10; y++) {

        if( chunk.tiles[x,y] != 0 || visited[x,y] != 1 ){ //air or already visited

            _currentIsland = new byte[ 10, 10 ];

            Queue<Vector2> toCheck = new Queue<Vector2>();
            toCheck.Enqueue( new Vector2(x,y) );

            while( toCheck.Count > 0 )
            {
                Vector2 curr = toCheck.Dequeue();

                int[] rowNbr = {-1, -1, -1,  0,  0,  1, 1, 1};
                int[] colNbr = {-1,  0,  1, -1,  1, -1, 0, 1};

                // Mark this cell as visited
                _currentIsland[x,y] = 1;
                visited[x,y] = 1;

                // Recur for all connected neighbours
                for (int k = 0; k < 8; ++k)
                {
                    if ( isSafe ((int)curr.x + rowNbr [k], (int)curr.y + colNbr [k], visited ))
                        {
                            Vector2 n = new Vector2( curr.x  + rowNbr[k], curr.y + colNbr[k] );
                            toCheck.Enqueue(n);
                        }
                    }
                }

                if( _currentIsland.Length > 0 )
                    islands.Add( _currentIsland );

            }
        }
    }

    bool isSafe( int x, int y, byte[,] visited )
    {
        return (InScope (x, y) && visited [x, y] == 0 && chunk.tiles[x,y] > 0 );
    }

谢谢,C。

【问题讨论】:

  • 希望有人指出这个问题有什么问题,而不是简单地标记它
  • 您能否详细说明您遇到的确切异常(类型、消息、堆栈跟踪)?
  • 你也可以发布isSafe的代码吗?由于您最终可能会为每个出队的向量在队列中放置多达 8 个向量,如果 isSafe 大部分返回 true,则可能会失去控制。
  • OutOfMemoryException: Out of memory System.Collections.Generic.Queue1[UnityEngine.Vector2].SetCapacity (Int32 new_size) System.Collections.Generic.Queue1[UnityEngine.Vector2].Enqueue (Vector2 item) MeshGenerator.FindIslands () (at Assets/Scripts/MeshGenerator.cs:130) GridManager.Update () (at Assets/Scripts/GridManager.cs:325) 这是个例外,谢谢。也使用 isSafe 方法编辑问题
  • 我假设 InScope 如果 (x,y) 在 (0,0) 到 (9,9) 方格之外则返回 false,对吗?

标签: c# unity3d queue


【解决方案1】:

我认为这里的问题是您没有跟踪您在队列中查看的邻居。

所以一开始你在 (0,0) 并且可以将以下向量添加到队列中

(1,0)、(0,1) 和 (1,1)

现在对于 (1,1),它将查看 (0,0),但 isSafe 将返回 false,因为您将 vistied[0,0] 设置为 1。但它也会添加 (1,0) 和(0,1) 将没有访问过的设置为 1,然后将依次添加 (1,1) 等等。基本上,您需要跟踪您见过的邻居。我猜您需要更改以下行

visited[x,y] = 1;

vistited[curr.x,curr.y] = 1;

但我不完全确定您的代码的意图,但这就是为什么它可能会耗尽内存,一遍又一遍地将相同的向量值放入队​​列中。

【讨论】:

  • 代表我的典型疏忽,感谢您发现这一点。它解决了内存异常,但代码根本上是错误的:(目的是找到并存储我网格中的所有岛屿。
猜你喜欢
  • 1970-01-01
  • 2018-11-13
  • 2016-05-13
  • 1970-01-01
  • 2015-07-13
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多