基于DFS识别2D瓦片地图岛屿时栈溢出问题求助
问题:DFS识别2D瓦片地图岛屿时的栈溢出问题
我在2D瓦片地图上使用DFS(深度优先搜索)识别醉汉行走算法生成的岛屿(作为横版卷轴游戏的平台),以便后续在这些平台上合理放置山丘。目前遇到的问题是:对地图外围区域执行DFS时会出现栈溢出,此时传递的std::vector元素数量约达3000个;而识别内部小岛屿(元素数量约20-50个)则无异常。
我使用伪地图(值为0、1、2)标记状态:
- 1:存在未检查的瓦片
- 0:无瓦片
- 2:已发现并加入岛屿列表
相关调用代码如下:
if (pseudoMap[y][x] == 1) { Uint8 platform = 1; PlatformDFS(&pseudoMap, x, y, &platform, visitedPlatform); if (platform == 1) { SDL_SetRenderDrawColor(graphicsRef->GetRenderer(), 0, 0, 255, 255); platformsFound.push_back(visitedPlatform); for (Vector2 gridPos : visitedPlatform) { tileMap[(int)gridPos.y][(int)gridPos.x]->SetTileLayer(TileLayer::Platform); SDL_Rect r((int)gridPos.x * 5, int(gridPos.y) * 5, 5, 5); SDL_RenderDrawRect(graphicsRef->GetRenderer(), &r); SDL_RenderPresent(graphicsRef->GetRenderer()); } PrintTileMapToConsole(1); std::cout << "Platform found starting at " << x << "," << y << std::endl; } else { std::cout << " NO platform found at " << x << "," << y << std::endl; visitedPlatform.clear(); } }
我向DFS函数传递以下参数:伪地图指针、当前待检查的x/y坐标、越界时会被设为0的标记(表示当前检查的是洞穴本身)、当前岛屿/平台的瓦片列表。DFS函数及边界检查代码如下:
void TileManager::PlatformDFS(std::vector<std::vector<Uint8>>* pmap, int x, int y, Uint8* platformFlag, std::vector<Vector2>& platformTiles) { if (IsNotInBounds(x, y)) { platformFlag = 0; return; } if ((*pmap)[y][x] != 1) return; Vector2 pos = Vector2(x, y); platformTiles.push_back(pos); // <--- 问题出在这里,检查洞穴外围时会出现栈溢出 (*pmap)[y][x] = 2; PlatformDFS(pmap, x, y + 1, platformFlag, platformTiles); PlatformDFS(pmap, x, y - 1, platformFlag, platformTiles); PlatformDFS(pmap, x + 1, y, platformFlag, platformTiles); PlatformDFS(pmap, x - 1, y, platformFlag, platformTiles); PlatformDFS(pmap, x + 1, y + 1, platformFlag, platformTiles); PlatformDFS(pmap, x - 1, y - 1, platformFlag, platformTiles); PlatformDFS(pmap, x + 1, y - 1, platformFlag, platformTiles); PlatformDFS(pmap, x - 1, y + 1, platformFlag, platformTiles); } bool TileManager::IsNotInBounds(int x, int y) { return y < 0 || y >= tileMap.size() || x < 0 || x >= tileMap[y].size(); }

图中蓝色框为已标记的平台,说明该逻辑在小范围内有效。
内容的提问来源于stack exchange,提问作者Ian
相关产品推荐
相关产品推荐

