Алгоритм створення лабіринту: відмінності між версіями

[неперевірена версія][неперевірена версія]
Вилучено вміст Додано вміст
Рядок 186:
 
/**
* Створює лабіринт з графу сітки, використовуючи <em>рандомізований пошук у глибину</em>.
* Creates a maze from a grid graph using <em>randomized depth-first search</em>.
*
* @author Armin Reichert
Рядок 193:
 
public static void main(String[] args) {
// Використання рекурсивної процедури:
// Using recursive procedure:
System.out.println(maze(10, 10, 0, 0, true));
// Використання нерекурсивної процедури:
// Using non-recursive procedure:
System.out.println(maze(10, 10, 0, 0, false));
}
 
/** Повертає лабіринт заданого розміру початкової генерації в даній позиції сітки. */
/** Returns a maze of the given size starting generation at the given grid position. */
public static Grid maze(int numCols, int numRows, int startCol, int startRow, boolean recursive) {
Grid grid = new Grid(numCols, numRows);
Рядок 212:
}
 
/** Рекурсивна процедура, що проходить через сітку і створює лабіринт (остовне дерево). */
/** Recursive procedure traversing the grid and creating the maze (spanning tree). */
private static void traverseRecursive(Grid grid, int v, BitSet visited) {
visited.set(v);
Рядок 221:
}
 
/** Нерекурсивна процедура, що проходить через сітку і створює лабіринт (остовне дерево). */
/** Non-recursive procedure traversing the grid and creating the maze (spanning tree). */
private static void traverseUsingStack(Grid grid, int v, BitSet visited) {
Deque<<nowiki>Integer</nowiki>> stack = new ArrayDeque<>();
Рядок 241:
}
 
/** Повертає випадковий напрямок невідомому сусіду або {@code -1}. */
/** Returns a random direction to an unvisited neighbor or {@code -1}. */
private static int unvisitedDir(Grid grid, int v, BitSet visited) {
int[] candidates = new int[4];
Рядок 263:
 
/**
* Реалізація сітки графу. Набір ребер представлений одним набором бітів.
* Grid graph implementation. Edge set is represented by a single bit-set.
*/
public class Grid {
 
/** DirectionsНапрямки. */
public static final int NORTH = 0, EAST = 1, SOUTH = 2, WEST = 3;
 
/** OppositeПротилежні directionsнапрямки. */
public static final int[] OPPOSITE = { SOUTH, WEST, NORTH, EAST };
 
/* DirectionНапрямні vectorsвектори. */
public static final int[] X = { 0, 1, 0, -1 };
public static final int[] Y = { -1, 0, 1, 0 };
 
/** Індекс не представляє вершини. */
/** Index representing no vertex. */
public static final int NO_VERTEX = -1;
 
/** Кількість стовпців сітки. */
/** Number of grid columns. */
public final int numCols;
 
/** NumberКількість ofрядків grid rowsсітки. */
public final int numRows;
 
private BitSet edges;
 
/** TheІндекс bit-setбітового indexнабору ofребра, theщо edgeзалишає leaving vertexвершину {@code v} towardsдо directionнапрямку {@code dir}. */
private int bit(int v, int dir) {
return 4 * v + dir;
}
 
/** Створює порожню сітку заданого розміру. */
/** Creates an empty grid of the given size. */
public Grid(int numCols, int numRows) {
this.numCols = numCols;
Рядок 300:
}
 
/** VertexВершина atв columnколонці {@code col} andі rowв рядку {@code row}. */
public int vertex(int col, int row) {
return numCols * row + col;
}
 
/** ColumnСтовпчик of vertexвершини {@code v}. */
public int col(int v) {
return v % numCols;
}
 
/** RowРядок of vertexвершини {@code v}. */
public int row(int v) {
return v / numCols;
}
 
/** Повертає кількість (неорієнтованих) ребер. */
/** Returns the number of (undirected) edges. */
public int numEdges() {
return edges.cardinality() / 2;
}
 
/** AddsДодає theребро edgeз from vertexвершини {@code v} towardsдо directionнапрямку {@code dir}. */
public void addEdge(int v, int dir) {
edges.set(bit(v, dir));
Рядок 326:
}
 
/** TellsВказує, ifчи theребро edgeвід from vertexвершини {@code v} towardsдо directionнапрямку {@code dir} existsіснує. */
public boolean hasEdge(int v, int dir) {
return edges.get(bit(v, dir));
Рядок 332:
 
/**
* ReturnsПовертає theсусіда neighbor of vertexвершини {@code v} towardsдо directionнапрямку {@code dir} orабо {@link #NO_VERTEX}.
*/
public int neighbor(int v, int dir) {
Рядок 339:
}
 
/** Повертає текстове представлення цієї сітки. */
/** Returns a textual representation of this grid. */
@Override
public String toString() {