迷宫问题
OJ链接:迷宫问题
题目:
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)
题目分析:
1.首先因为求最短一般我们采用BFS
2.因为要输出路径,所以我们肯定要有一个队列或者别的数据结构来存储路径
3.因为只需要输出最短路径,我们要记录最短的路径,所以节点必须设置前后节点的连接 或者使用倒推的方式
4.模板套路
题目代码:
package javaBase;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
class Node {
int row; //当前的行列
int column;
int father_x; //父节点
int father_y;
int length; //长度
public Node(int row, int column,int father_x, int father_y, int length) {
super();
this.row = row;
this.column = column;
this.father_x= father_x;
this.father_y = father_y;
this.length = length;
}
public Node() {}
}
public class Main{
private static int data[][] = new int[5][5];
private static LinkedList<Node> stack = new LinkedList<Node>();
private static int next[][] = { { 0, 1 }, { 1, 0 } ,{0,-1},{-1,0}};// 4个方向
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
for(int i=0;i<5;i++) {
String ss = s.nextLine();
String [] temp = ss.split(" ");
for(int j=0;j<5;j++) {
data[i][j]=Integer.parseInt(temp[j]);
}
}
bfs(4, 4);
Node node = stack.poll();
int a=node.row;
int b=node.column;
System.out.println("("+node.row+","+node.column+")");
while(!stack.isEmpty()) {
Node node3 = stack.poll();
if(node3.father_x==a && node3.father_y==b) {
System.out.println("("+node3.row+","+node3.column+")");
a=node3.row;
b=node3.column;
}
}
}
public static void bfs(int m,int n) {//m n 分别为 目标点 横坐标和纵坐标
Queue<Node> queue = new LinkedList<Node>();
Node node1 = new Node(0, 0,-1,-1, 1);
queue.offer(node1);
while(!queue.isEmpty()) {
Node node2 = queue.poll();
stack.add(node2);
if(node2.row==m && node2.column==n) {
// System.out.println(node2.length); //记录一共几步
break;
}
for(int i=0;i<4;i++) {
int temp1 = node2.row+next[i][0];
int temp2 = node2.column+next[i][1];
if(temp1>4 || temp2>4 || temp1<0 || temp2<0 ||data[temp1][temp2]==1) {
continue;
}
data[temp1][temp2]=1; //也可以使用visit标记,这里直接修改原数组
queue.add(new Node(temp1,temp2,node2.row,node2.column,node2.length+1));
}
}
}
}