迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 25012 | Accepted: 14607 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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的题,bfs的模板不再赘述,强调两个问题
①定义了两个数组存储数据,map数组存储5x5的矩阵,address数组存储每个点的“父节点”
②一般bfs都是打印最短路径的长度,这个题让把路径打印出来,所以不是找到就完了,还要记录,这也是
为什么定义了address数组,从(0,0)找到了(4,4)之后可以利用栈的思想回溯找回去,再倒着打印出来
也可以从一开始就从(4,4)向(0,0)找,回溯打印就好。
代码如下:
import java.util.*;
public class Main
{
public static int[][] map = new int[6][6];
public static Point[][] address = new Point[6][6];
public static Queue<Point> queue = new LinkedList();
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
for(int i=0 ; i<5 ; i++)
{
for(int j=0 ; j<5 ; j++)
{
map[i][j] = in.nextInt();
}
}
bfs();
show();
}
public static void bfs()
{
int[] x_go = {0,0,1,-1};
int[] y_go = {1,-1,0,0};
queue.add(new Point(4,4));
while(!queue.isEmpty())
{
Point p = queue.peek();
queue.poll();
int temx,temy;
if(p.x==0&&p.y==0)break;
for(int i=0 ; i<4 ; i++)
{
temx = p.x+x_go[i];
temy = p.y+y_go[i];
if(temx<0||temy<0||temx==5||temy==5)continue;
if(map[temx][temy]==1)continue;
map[temx][temy]=1;
address[temx][temy]=p;
queue.add(new Point(temx,temy));
}
}
queue.clear();
}
public static void show()
{
int temx=0,temy=0;
while(true)
{
System.out.printf("(%d, %d)\n",temx,temy);
if(temx==4&&temy==4)break;
int xx = temx;
temx = address[temx][temy].x;
temy = address[xx][temy].y;
}
}
}
class Point
{
public int x;
public int y;
public Point(int x,int y)
{
this.x = x;
this.y = y;
}
}