2017-01-22 26 views
0

我想做廣度優先搜索算法作爲迷宮求解器。迷宮是由一個TableLayoutPanel構成的。如何以不同的方式命名Hashtable中的按鍵

我有這樣的事情:

Hashtable hash = new Hashtable(); 
    Queue<TableLayoutPanelCellPosition> q_cellposition = new Queue<TableLayoutPanelCellPosition>(); 
    while (q_cellposition.Count != 0) 
     { 
      TableLayoutPanelCellPosition currentPosition = q_cellposition.Dequeue(); 
      TableLayoutPanelCellPosition left = new TableLayoutPanelCellPosition(currentPosition.Column - 1, currentPosition.Row); 
      Label leftN = (Label)tlp.GetControlFromPosition(left.Column, left.Row); 
      TableLayoutPanelCellPosition right = new TableLayoutPanelCellPosition(currentPosition.Column + 1, currentPosition.Row); 
      Label rightN = (Label)tlp.GetControlFromPosition(right.Column, right.Row); 

      hash.Add(leftN, currentPosition); 
      q_cellposition.Enqueue(left); 

      hash.Add(rightN, currentPosition); 
      q_cellposition.Enqueue(right); 
     } 

現在,在第一次迭代之後,它顯然試圖將新KeyValuePair添加到哈希表。然而,它將新的leftN鍵和rightN鍵看作相同的標籤(儘管它們在技術上不是這樣),並且它引發了錯誤,即該鍵已被添加。我想我每次向Hashtable添加內容時都必須更改密鑰的名稱。我現在的問題是:我如何有效地做到這一點?

回答

0

I believe that some consider the Hashtable obsolete或劣於通用Dictionary對象,你應該使用它。

I think you might be able to use the array operator訪問並替換已在DictionaryHashtable中的密鑰,但不會引發該密鑰已存在的異常。

Add更多用於當您知道密鑰尚未在Hashtable中時。除非你需要爲每個項目創建的唯一密鑰,即使它們共享相同的密鑰

hash.Add(leftN, currentPosition); 

hash[leftN] = currentPosition; 

所以Add語句會改變而來。在這一點上,儘管您可能會切換到一個密鑰生成方法,通過在密鑰生成期間添加另一個變量來使這些相同的密鑰不同,或者您需要切換到另一個更合適的數據結構。

如果你的鑰匙總是敲擊,你可能會說左右分隔成兩個不同的哈希表,但我懷疑這是你想要的。或者您可以將當前迭代的前綴添加到鍵的前面。但是在那個時候,你可能會使用通用的Stack object

相關問題