2014-05-13 33 views
0

我正在尋找一種方法來獲取在w * h網格中放置n個對象的所有可能組合。 我需要回答的是這樣一個問題:一個人可以在棋盤上放置n個棋子。因此,例如對於兩個棋子和2x2格,我的預期結果是:在網格上查找placemenet的所有可能組合

((0, 0, "p1"), (0, 1, "p2")) 
((0, 0, "p1"), (1, 1, "p2")) 
((0, 0, "p1"), (1, 0, "p2")) 
((0, 1, "p1"), (1, 1, "p2")) 
((0, 1, "p1"), (0, 0, "p2")) 
((0, 1, "p1"), (1, 0, "p2")) 
((1, 0, "p1"), (0, 1, "p2")) 
((1, 0, "p1"), (1, 1, "p2")) 
((1, 0, "p1"), (0, 0, "p2")) 
((1, 1, "p1"), (0, 0, "p2")) 
((1, 1, "p1"), (0, 1, "p2")) 
((1, 1, "p1"), (1, 0, "p2")) 

我該如何在Java中執行此操作?

回答

0

將所有項目放入集合中,將所有位置放入集合中,迭代檢查是否存在衝突。

boolean foundNewSolutionLastIteration = true; 
while (foundNewSolutionLastIteration) { 
    foundNewSolutionLastIteration = false; 
    List<Pawn> pawns = new ArrayList<Pawn>() 
    ... Fill the colelction ... 
    List<GridSquare> positions = new ArrayList<GridSquare() 
    ... Fill the collection ... 
    for (Pawn p : pawns) { 
     for (GridSquare square : positions) { 
      ... Check if gridsquare contains pawn, else put it in there 
      ... Check if all pawns have been placed if so it's a valid position 
      ... Is this a new solution? if so set foundNewSolutionLastIteration to true 
     } 
    } 
} 

每次迭代shouild recford的位置,因此它可以被排除在格蘭下一個循環

+0

嗨,你的解決方案會給我將棋子的一個可能的解決辦法,我要的是找出所有這些解決方案。我可能寫得不夠清楚 - 我需要的結果是集合的集合,並且在每個集合中都應該有n個三元組,如(0,0,「p1」),(0,1,「p2」),。 ..(每個集合包含一個解決方案)。 – gysyky

+0

你需要把它放到一個循環中並遍歷它,直到你找不到新的解決方案......(我已經編輯了答案來反映這一點) –