【发布时间】:2017-04-29 22:12:18
【问题描述】:
问题是一个二元迷宫,其中 1 是墙壁,0 是有效路径。你从左上角(0,0)开始,你必须到达右下角(宽度-1,高度-1)。您必须找到从左上角到右下角的最短路径。出现扭曲是因为您最多只能拆除一堵墙,这是让我感到困惑的部分。我当前的代码可以解决最短路径,而无需计算要拆除的墙。
这里有几个例子: [0,1,1,0], [0,0,0,1], [1,1,0,0], [1,1,1,0] 答:7招(包括进出)
示例 2: [0,0,0,0,0],[0,1,1,1,0],[1,0,0,0,0],[0,1,1,1,1],[0 ,1,1,1,1],[0,0,0,0,0] 答案:11(因为你可以在[0][1]位置打破墙,让路径变短)
所以就像我之前所说的,我的代码会找到最短路径,但目前不会尝试为更短的路径移除墙,主要是因为我不明白如何去做。我在想我一次移除一堵墙并不断重新运行以查看是否产生了更短的路径,但这似乎非常昂贵的操作,但它可能会完成工作。不过,我希望我能找到一种更清晰、更简单的方法。
import java.util.*;
public class Maze {
public static void main(String [] args)
{
int[][] arr = new int[][] {
{0,0,0,0,0},
{1,1,1,1,0},
{0,0,0,0,0},
{0,1,1,1,1},
{0,1,1,1,1},
{0,0,0,0,0},
};
answer(arr);
}
public static int answer(int[][] maze) {
maze[maze.length-1][maze[0].length -1] = 9;
Point p = getPathBFS(0,0,maze);
int length = 1;
while(p.getParent() != null) {
p = p.getParent();
length++;
}
System.out.println(length);
return length;
}
private static class Point {
int x;
int y;
Point parent;
public Point(int x, int y, Point parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent() {
return this.parent;
}
}
public static Queue<Point> q = new LinkedList<Point>();
public static Point getPathBFS(int x, int y,int[][] arr) {
q.add(new Point(x,y, null));
while(!q.isEmpty()) {
Point p = q.remove();
if (arr[p.x][p.y] == 9) {
return p;
}
if(isFree(p.x+1,p.y,arr)) {
arr[p.x][p.y] = -1;
Point nextP = new Point(p.x+1,p.y, p);
q.add(nextP);
}
if(isFree(p.x-1,p.y,arr)) {
arr[p.x][p.y] = -1;
Point nextP = new Point(p.x-1,p.y, p);
q.add(nextP);
}
if(isFree(p.x,p.y+1,arr)) {
arr[p.x][p.y] = -1;
Point nextP = new Point(p.x,p.y+1, p);
q.add(nextP);
}
if(isFree(p.x,p.y-1,arr)) {
arr[p.x][p.y] = -1;
Point nextP = new Point(p.x,p.y-1, p);
q.add(nextP);
}
}
return null;
}
public static boolean isFree(int x, int y,int[][] arr) {
if((x >= 0 && x < arr.length) && (y >= 0 && y < arr[x].length) && (arr[x][y] == 0 || arr[x][y] == 9)) {
return true;
}
return false;
}
}
【问题讨论】:
标签: java breadth-first-search maze graph-layering