POJ3984(BFS)
迷宫问题
Description
定义一个二维数组:
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)
题意
略。
思路
使用BFS从(0,0)开始搜索,用队列记录搜索的过程,直到右下角(4,4),输出路径即可。
代码
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Maze {
int[][] map = new int[5][5];//迷宫地图
int[][] direction = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};//四个方位
int[][] visit = new int[5][5];//记录是否已经访问过
List<Node> queue = new ArrayList<Node>();//队列
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Maze maze = new Maze();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
maze.map[i][j] = sc.nextInt();
maze.visit[i][j] = 0;
}
}
maze.bfs(0, 0, 4, 4);
maze.print(maze.queue.size() - 1);
}
public void bfs(int startX, int startY, int endX, int endY) {
visit[startX][startY] = 1;
Node node = new Node();
node.setX(startX);
node.setY(startY);
node.setPre(-1);
queue.add(node);
int rear = 1;//队尾
int front = 0;//队头
while (front < rear) {//对列不为空
for (int i = 0; i < 4; i++) {//遍历上下左右4个方位的点
int nextX = queue.get(front).getX() + direction[i][0];
int nextY = queue.get(front).getY() + direction[i][1];
if (nextX < 0 || nextX >= 5 || nextY < 0 || nextY >= 5 || visit[nextX][nextY] == 1 || map[nextX][nextY] == 1) {
//是否在迷宫内,是否已访问过,是否是墙壁。
continue;
}
Node tmp = new Node();
tmp.setX(nextX);
tmp.setY(nextY);
tmp.setPre(front);
queue.add(tmp);
rear++;
visit[nextX][nextY] = 1;
if (nextX == endX && nextY == endY) {
return;
}
}
front++;//出队
}
}
public void print(int now) {
if (queue.get(now).getPre() == -1) {
System.out.println("(" + queue.get(now).getX() + ", " + queue.get(now).getY() + ")");
} else {
print(queue.get(now).getPre());
System.out.println("(" + queue.get(now).getX() + ", " + queue.get(now).getY() + ")");
}
}
static class Node {
private int x;
private int y;
private int pre;
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getPre() {
return pre;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setPre(int pre) {
this.pre = pre;
}
}
}