定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
一看数据范围,5x5的数组,好的,放肆宽搜稳了。唯一比较麻烦的是还要输出路径,这就很扑街啊,还要想办法记录一下。
一开始一边看题一边条件反射的敲了个int二维数组,然后开始打宽搜,打着打着越想越多,补上了越来越多的东西(记录坐标,记录路径…..)。
感觉不太好…..想了一下,推翻了重写,直接开了一个class,定义了x坐标、y坐标,顺便写成了链表方便记录路径….把数组直接改成了自己写的新对象的数组。
居然直接就ac了….这种写的时候已经把所有情况都考虑好的感觉真爽,虽然这题很水。
AC代码:
public class Main {
static Position[][] maze = new Position[8][8];
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 8; i++) {// 全部初始化,不然搜索的时候会报错
for (int j = 0; j < 8; j++) {
maze[i][j] = new Position(i, j, 1);// 人工建墙,围上迷宫,免得判范围
}
}
int[][] operate = { { 0, -1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };// 表驱动法代替连续if
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
maze[i][j].value = reader.nextInt();
}
}
Queue wait = new LinkedList();
wait.add(maze[1][1]);
while (!wait.isEmpty()) {
Position cur = wait.poll();
if (cur.x == 5 && cur.y == 5) {
// 写了个递归,从终点开始回退,到达起点为止开始输出,达到题目从头输出的要求
outPut(5, 5);
break;
}
cur.value = 1;// 标记为走过
for (int i = 0; i < 4; i++) {
int nextX = cur.x + operate[i][0];
int nextY = cur.y + operate[i][1];
if (maze[nextX][nextY].value == 0) {
wait.add(maze[nextX][nextY]);
maze[nextX][nextY].pre = cur;// 链式记录
}
}
}
}
public static void outPut(int x, int y) {
if (maze[x][y].pre == null) {
System.out.println("(0, 0)");
return;
}
outPut(maze[x][y].pre.x, maze[x][y].pre.y);
int realX = x - 1;
int realY = y - 1;
System.out.println("(" + realX + ", " + realY + ")");
}
}
class Position {
int x;
int y;
int value;
Position pre;
public Position(int x, int y, int value) {
this.x = x;
this.y = y;
this.value = value;
}
}
测试的时候感觉会跳错,因为最近打题总是出各种神奇的bug,结果直接出正确答案了。想起来初中用记事本写mod的时候,连续半年控制台编译前几次肯定会报错,要调好久,直到有一天写(chao)了很长的自己都半猜测性质的代码,却一发编译通过,而且100%达到了我想要的功能。
那时候真是….超级感动。