使用BFS查找网格上对象的可能路径数

问题描述 投票:3回答:1

我有一个表示网格的矩阵,想要找出一个对象可以移动到的所有可能的位置。

对象只能水平或垂直移动。

让我们假设下面的例子是我正在看的网格,它表示为2d矩阵。对象是*,0是对象可以移动到的空白空间,1是对象无法跳过或继续的墙。

找到此对象的所有可能移动的最佳方法是什么,只要它只能水平或垂直移动?

我想打印一条消息说:“对象有9个地方可以去。” 9是以下示例,但我希望它适用于以下网格的任何配置。所以我所要做的就是给出*的当前坐标,它将给出我可以移动到的可能位置的数量。

需要注意的是,在计算中不考虑*的原始位置,这就是为什么对于下面的示例,消息将打印9而不是10。

我有一个isaWall方法告诉我细胞是否是一堵墙。 isaWall方法在Cell类中。每个单元格由其坐标表示。我研究过使用像BFS或DFS这样的算法,但我不太明白在这种情况下如何实现它们,因为我对算法不太熟悉。我想过将Cells用作图的节点,但是不太清楚如何遍历图,因为从我在网上看到的BFS和DFS的例子中,你通常会有一个目标节点和源节点(源是*)的位置,但在这种情况下我没有真正的目标节点。我真的很感激一些帮助。

00111110
01000010
100*1100
10001000
11111000

编辑:我检查了评论中推荐的网站,并尝试实现我自己的版本。遗憾的是没有用。我知道我必须扩展“前沿”,我基本上只是将扩展代码翻译成Java,但它仍然无效。该网站继续解释该过程,但在我的情况下,没有目的地单元格去。我真的很感激有关我案子的例子或更明确的解释。

EDIT2:我还是很困惑,请有人帮忙吗?

java depth-first-search breadth-first-search
1个回答
2
投票

虽然BFS / DFS通常用于查找起点和终点之间的连接,但实际上并非如此。 BFS / DFS是“图遍历算法”,这是一种奇特的方式,它说他们发现从起点可以到达的每个点。 DFS(深度优先搜索)更容易实现,因此我们将根据您的需要使用它(注意:当您需要找到距起点有多远的点时使用BFS,并且只在您需要时使用DFS去每一点)。

我不确切知道你的数据是如何构造的,但是我假设你的地图是一个整数数组并定义了一些基本功能(为了简单起见,我创建了起始单元格2):

map.Java

import java.awt.*;

public class Map {
    public final int width;
    public final int height;

    private final Cell[][] cells;
    private final Move[] moves;
    private Point startPoint;

    public Map(int[][] mapData) {
        this.width = mapData[0].length;
        this.height = mapData.length;

        cells = new Cell[height][width];
        // define valid movements
        moves = new Move[]{
            new Move(1, 0),
            new Move(-1, 0),
            new Move(0, 1),
            new Move(0, -1)
        };

        generateCells(mapData);
    }

    public Point getStartPoint() {
        return startPoint;
    }

    public void setStartPoint(Point p) {
        if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");

        startPoint.setLocation(p);
    }

    public Cell getStartCell() {
        return getCellAtPoint(getStartPoint());
    }

    public Cell getCellAtPoint(Point p) {
        if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");

        return cells[p.y][p.x];
    }

    private void generateCells(int[][] mapData) {
        boolean foundStart = false;
        for (int i = 0; i < mapData.length; i++) {
            for (int j = 0; j < mapData[i].length; j++) {
                /*
                0 = empty space
                1 = wall
                2 = starting point
                 */
                if (mapData[i][j] == 2) {
                    if (foundStart) throw new IllegalArgumentException("Cannot have more than one start position");

                    foundStart = true;
                    startPoint = new Point(j, i);
                } else if (mapData[i][j] != 0 && mapData[i][j] != 1) {
                    throw new IllegalArgumentException("Map input data must contain only 0, 1, 2");
                }
                cells[i][j] = new Cell(j, i, mapData[i][j] == 1);
            }
        }

        if (!foundStart) throw new IllegalArgumentException("No start point in map data");
        // Add all cells adjacencies based on up, down, left, right movement
        generateAdj();
    }

    private void generateAdj() {
        for (int i = 0; i < cells.length; i++) {
            for (int j = 0; j < cells[i].length; j++) {
                for (Move move : moves) {
                    Point p2 = new Point(j + move.getX(), i + move.getY());
                    if (isValidLocation(p2)) {
                        cells[i][j].addAdjCell(cells[p2.y][p2.x]);
                    }
                }
            }
        }
    }

    private boolean isValidLocation(Point p) {
        if (p == null) throw new IllegalArgumentException("Point cannot be null");

        return (p.x >= 0 && p.y >= 0) && (p.y < cells.length && p.x < cells[p.y].length);
    }

    private class Move {
        private int x;
        private int y;

        public Move(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }
    }
}

cell.Java

import java.util.LinkedList;

public class Cell {
    public final int x;
    public final int y;
    public final boolean isWall;
    private final LinkedList<Cell> adjCells;

    public Cell(int x, int y, boolean isWall) {
        if (x < 0 || y < 0) throw new IllegalArgumentException("x, y must be greater than 0");

        this.x = x;
        this.y = y;
        this.isWall = isWall;

        adjCells = new LinkedList<>();
    }

    public void addAdjCell(Cell c) {
        if (c == null) throw new IllegalArgumentException("Cell cannot be null");

        adjCells.add(c);
    }

    public LinkedList<Cell> getAdjCells() {
        return adjCells;
    }
}

现在编写我们的DFS功能。 DFS通过以下步骤递归触摸每个可到达的单元格一次:

  1. 将当前单元标记为已访问
  2. 循环通过每个相邻的细胞
  3. 如果尚未访问该单元,则DFS表示该单元,并将该单元附近的单元数添加到当前计数器中
  4. 返回与当前单元格相邻的单元格数+ 1

你可以看到这个here的可视化。有了我们编写的所有帮助功能,这很简单:

map helper.Java

class MapHelper {
    public static int countReachableCells(Map map) {
        if (map == null) throw new IllegalArgumentException("Arguments cannot be null");
        boolean[][] visited = new boolean[map.height][map.width];

        // subtract one to exclude starting point
        return dfs(map.getStartCell(), visited) - 1;
    }

    private static int dfs(Cell currentCell, boolean[][] visited) {
        visited[currentCell.y][currentCell.x] = true;
        int touchedCells = 0;

        for (Cell adjCell : currentCell.getAdjCells()) {
            if (!adjCell.isWall && !visited[adjCell.y][adjCell.x]) {
                touchedCells += dfs(adjCell, visited);
            }
        }

        return ++touchedCells;
    }
}

就是这样!如果您需要有关代码的任何解释,请与我们联系。

© www.soinside.com 2019 - 2024. All rights reserved.