我也建議#1,但它並不像您認爲的圖表式數據結構那樣將附加數據存儲到鏈接節點的邊緣。
如果你想讓這個過程非常緊湊,你可以做的另一件事是讓這些邊(路徑)只存儲索引到MazeTile
而不是指針。使用索引,您可以將輔助數據存儲到高位中,例如,指示路徑是否被阻塞或您需要的任何內容。
編輯:
按照要求,這裏是一個更詳細一點的指數型解決方案。比方說,你這樣做:
class Pathway
{
public:
/// Creates a new pathway.
Pathway();
/// Sets the index of the neighboring maze tile/node.
void set_maze_tile(int new_index);
/// @return The index to the neighboring maze tile/node.
int maze_tile() const;
/// Sets whether the pathway is free or not.
void set_free(bool val);
/// @return True if the pathway is free.
bool is_free() const;
private:
int index;
};
要做到這一點就需要你來分配這些迷宮瓷磚到一些連續的內存塊(例如:使用std::vector
或某種其他動態數組 - 它沒有索引無效可以增長)。
現在你可以做這樣的事情:
enum
{
free_bit = 1 << (sizeof(int)*8 - 1),
index_mask = ~free_bit
};
Pathway::Pathway(): index(0)
{
}
void PathWay::set_maze_tile(int new_index)
{
const bool was_free = is_free();
index = new_index;
set_free(was_free);
}
int PathWay::maze_tile() const
{
return index & index_mask;
}
void PathWay::set_free(bool val)
{
if (val)
index |= free_bit;
else
index &= ~free_bit;
}
bool PathWay::is_free() const
{
return (index & free_bit) != 0;
}
這是一個有點醜陋,低級別的代碼風格,而這個接口是一個無聊的getter/setter樣的設計,但它會壁球您的途徑從64位(通常結構填充/對齊)佔用大約16個字節到僅僅4個字節,這應該不僅有助於減少內存使用,而且還會獲得更多的速度(更大的空間局部性,更多的相鄰路徑擬合進入緩存行)。
它確實降低了從2^31到2^30的無符號索引範圍(允許大約10億個迷宮塊)。您可以使用unsigned int
將範圍加倍到2^31(儘管除非您真正打算處理接近該比例的東西,否則它可能不值得費心。
我不使用多維數組的唯一原因是我想玩這個問題的數據結構。實際上,迷宮永遠不會比20x20大,但我希望它在理論上可以很好地擴展。 –
@LucaFülbierI see;)那麼,根據編程語言的不同,可以使用稀疏數組來處理縮放。但是,當然如果不知道所有的細節,就不能推薦具體的東西。 –
你可以說我正在嘗試爲了學習的目的而重新發明半個輪子;-) –