我正在寻找一种方法来获得在w * h网格中放置n个对象的所有可能组合。 我需要回答的问题是:在棋盘上放置棋子的方式是什么?因此,例如对于两个棋子和2x2网格,我的预期结果将是:
((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 :(得分: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
}
}
}
每次迭代都要重新定位,以便在下一个循环中排除它