Пример #1
0
  @Override
  public Point[] findPath(Maze maze) {
    cols = maze.cols;
    rows = maze.rows;
    Cell[][] cells = new Cell[maze.rows][maze.cols];
    Set<Cell> cellSet = new HashSet<>();
    for (int j = 0; j < maze.rows; j++) {
      for (int i = 0; i < maze.cols; i++) {
        Cell cell = new Cell(i, j, maze.data[i][j]);
        cells[j][i] = cell;
        cellSet.add(cell);
      }
    }

    Cell start = cells[0][0];
    start.distance = 0;
    Cell finish = cells[rows - 1][cols - 1];
    int wave = 0;
    do {
      for (Cell cell : cellSet) {
        if (cell.distance == wave) {
          List<Cell> neighbors = cell.getNeighbors(cellSet);
          for (Cell neighbor : neighbors) {
            if (neighbor.distance == -1) {
              neighbor.distance = wave + 1;
            }
          }
        }
      }
      wave++;
    } while (finish.distance == -1);
    List<Cell> path = new ArrayList<>();
    path.add(finish);
    Cell currCell = finish;
    while (!path.contains(start)) {
      assert currCell != null;
      currCell = getNearest(currCell.getNeighbors(cellSet));
      path.add(currCell);
    }
    logger.debug("найден путь от выхода до входа, его длинна {}", wave);

    Point[] pathPoints = new Point[path.size()];
    for (int i = 0; i < pathPoints.length; i++) {
      pathPoints[i] = new Point(path.get(i).x, path.get(i).y);
    }
    logger.debug("обратный путь построен");
    return pathPoints;
  }
Пример #2
0
  @Override
  public Point[] findPath(Maze maze) {
    cols = maze.cols;
    rows = maze.rows;
    Cell[][] cells = new Cell[maze.rows][maze.cols];
    Set<Cell> cellSet = new HashSet<>();
    for (int y = 0; y < maze.rows; y++) {
      for (int x = 0; x < maze.cols; x++) {
        Cell cell = new Cell(x, y, maze.data[x][y]);
        cells[x][y] = cell;
        cellSet.add(cell);
      }
    }

    Cell start = cells[0][0];
    start.distance = 0;
    Cell finish = cells[rows - 1][cols - 1];
    int wave = 0;
    do {
      for (Cell cell : cellSet) {
        if (cell.distance == wave) {
          List<Cell> neighbors = cell.getNeighborCells(cellSet);
          for (Cell neighbor : neighbors) {
            if (neighbor.distance == -1) {
              neighbor.distance = wave + 1;
            }
          }
        }
      }
      wave++;
    } while (finish.distance == -1);
    List<Cell> path = new ArrayList<>();
    path.add(finish);
    Cell currCell = finish;
    while (!path.contains(start)) {
      assert currCell != null;
      currCell = getСlosest(currCell.getNeighborCells(cellSet));
      path.add(currCell);
    }
    logger.debug("Построен путь от входа к выходу длиной {}", wave);

    Point[] pathPoints = new Point[path.size()];
    for (int i = 0; i < pathPoints.length; i++) {
      pathPoints[i] = new Point(path.get(i).x, path.get(i).y);
    }

    return pathPoints;
  }