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 00 1 0 1 00 0 0 0 00 1 1 1 00 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一遍,数组dis存最短路径(此方法来自《挑战程序设计竞赛(第2版)》-宽度优先搜索,迷宫最短路径-P34)。但没办法记录走过的路径,那该怎么办呢?
我想到的是开一个pair数组sha,记录此点的上一个点的x和y。之后开循环,根据本x,y继续找上个x,y。最后判断sha是否x==0,y==0,如果满足,那么就退出循环。
我把答案存在了sta栈里(其实也可以存在数组里,最后倒输出即可。但作为一个合格的IT男,能装逼则装逼,呵呵:-D) 最后输出sta.top() 之后sta.pop() 最后答案即可求出。
AC代码:
#include#include #include #include #include #include