2

我在这里遵循本指南:http: //www.mazeworks.com/mazegen/mazetut/index.htm

或者更具体地

create a CellStack (LIFO) to hold a list of cell locations 
set TotalCells = number of cells in grid 
choose a cell at random and call it CurrentCell 
set VisitedCells = 1 

while VisitedCells < TotalCells 

find all neighbors of CurrentCell with all walls intact  
if one or more found 
    choose one at random 
    knock down the wall between it and CurrentCell 
    push CurrentCell location on the CellStack 
    make the new cell CurrentCell 
    add 1 to VisitedCells else 
    pop the most recent cell entry off the CellStack 
    make it CurrentCell endIf 

endWhile

我用java写这个,我的问题是。

我应该如何存储我访问过的单元格,以便我可以从放置它们时的相反顺序访问它们。

像这样?

List<Location> visitedCells = new ArrayList<Location>();

Then do I grab with visitedCells.get(visitedCells.size()-1)?

位置存储 x、y 和 z。不是我想问你的。

4

3 回答 3

3

LIFO 结构最好在 Java 中使用Deque对象而不是Stack. 该类Stack扩展Vector并仅为向后兼容而保留。

要使用Deque,最好的办法是使用LinkedList,它实现了Deque接口。

Deque<Location> locationStack = new LinkedList<Location>();

ArrayDeque

Deque<Location> locationStack = new ArrayDeque<Location>();

然后使用pushandpop方法来推送和弹出Location对象。

该类Stack有一堆或多或少无用的同步开销,只会导致您的代码在进入和退出同步代码时变慢。

于 2012-09-04T22:02:05.407 回答
3

您可以为此目的使用堆栈:

Stack<Location> visitedCells = new Stack<Location>();
visitedCells.push(myLocation1);
visitedCells.push(myLocation2);

// Get last one in but DONT remove
Location location2 = visitedCells.peek(); 

// Get last one in and remove
location2 = visitedCells.pop(); 
于 2012-09-04T21:36:24.053 回答
0

以下代码按您添加的顺序存储值。

List<Location> visitedCells = new ArrayList<Location>();

然后你可以打电话

Collections.reverse(visitedCells);

给你反向排序列表。

(或者)

您可以使用ArrayDeque

于 2012-09-04T21:32:45.710 回答