【问题标题】:Find a path of robot in a grid algorithm在网格算法中找到机器人的路径
【发布时间】:2017-11-05 11:54:03
【问题描述】:

从破解编码面试开始做这个练习:

一个机器人坐在网格的左上角,有 r 行和 c 列。机器人只能在两个方向上移动,向右和向下,但某些单元格是“禁区”,因此机器人无法踩到它们。设计一个算法来找到机器人从左上角到右下角的路径。

代码:

static int[][] MOVES = new int[][] { { 1, 0 }, { 0, 1 } };

private boolean isSafe(boolean[][] GRID, Point current) {
    if (current.row < 0 || current.row >= GRID.length 
        || current.col < 0 || current.col >= GRID[0].length 
                      || !GRID[current.row][current.col]) {
            return false;
    }
    return true;
}

/*** Check if there is a Path **/
public boolean getPath(boolean[][] grid, Point start, Point end, List<Point> path) {
    // if already reached, return true. The caller will print the path
    if (start.equals(end)) {
         return true;
    }
    // try out all the moves from the array.
    for (int i = 0; i < MOVES.length; i++) {
        int newRow = start.row + MOVES[i][0];
        int newCol = start.col + MOVES[i][1];
        Point current = new Point(newRow, newCol);
        // if it is safe to move, move forward
        if (isSafe(grid, current)) {
           // recursively try next targets and keep moving
           if (getPath(grid, current, end, path)) {
              // if the path lands up to destination, 
              // then the current position was also responsible for that,
              // hence add it to the path.
              path.add(current);
              return true;
           }
        }
    }
    return false;
}


public class Point {

    int row, col;

    public Point(int row, int col) {
        super();
        this.row = row;
        this.col = col;
    }
}

然后进行测试:

boolean[][] GRID = new boolean[][] { 
        { true, true, true, true, true, true },
        { true, true, true, true, true, true }, 
        { true, true, true, true, true, true },
        { true, true, true, true, true, true }, 
        { true, true, true, true, true, true },
        { true, true, true, true, true, true } };

Point start = new Point(0, 0);
Point end = new Point(GRID.length - 1, GRID[0].length - 1);
List<Point> path = new ArrayList<Point>();
path.add(start);
algo.getPath(GRID, start, end, path);
System.out.println( algo.getPath(GRID, start, end, path));

结果我总是得到false。我不明白代码有什么问题。

【问题讨论】:

  • 你调试了吗?您将问题范围缩小到了哪里?
  • 另外问题是找到路径,而不是检查是否存在。
  • 路径将在“路径”变量中。即使在本书提供的更正中,该方法也返回一个布尔值。

标签: java algorithm multidimensional-array


【解决方案1】:

这个条件永远不会成立:

if (start.equals(end)) {
    return true;
}

因为您没有在Point 中覆盖equals。 该类继承Object.equals的默认实现, 所以Point 的两个不同实例永远不会相等, 因为没有任何逻辑可以比较他们的rowcol 字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多