在网格算法中查找机器人的路径

时间:2017-06-04 16:53:54

标签: java algorithm multidimensional-array

通过破解编码面试来做这件事:

  

一个机器人坐在网格的左上角,有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。我不明白代码的错误。

1 个答案:

答案 0 :(得分:1)

这种情况永远不会成真:

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

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