http://poj.org/problem?id=3984
定义一个二维数组:
它表示一个迷宫,其中的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)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cstdio> #include <cstring> #include <stdlib.h> #include <math.h> #include <queue> #include <algorithm> using namespace std; #define maxn 521 #define INF 0xfffffff int maps[maxn][maxn]; int dir[4][2]= {{0,1},{1,0},{-1,0},{0,-1}}; struct node { int x, y; }a[maxn][maxn]; void DFS(int x, int y) { if(x == 0 && y == 0) { printf("(0, 0)\n"); return ; } DFS(a[x][y].x, a[x][y].y); printf("(%d, %d)\n",x, y); } void BFS() { int i; queue<node>Q; node begins, now, next; begins.x = 0; begins.y = 0; Q.push(begins); while(Q.size()) { now = Q.front(); Q.pop(); if(now.x == 4 && now.y == 4) return ; for(i=0; i<4; i++) { next.x = now.x + dir[i][0]; next.y = now.y + dir[i][1]; if(next.x>=0 && next.x<5 && next.y>=0 && next.y<5 && !maps[next.x][next.y]) { maps[next.x][next.y]=1; a[next.x][next.y] = now; Q.push(next); } } } } int main() { int i,j; for(i=0; i<5 ; i++) for(j=0; j<5; j++) scanf("%d", &maps[i][j]); BFS(); DFS(4, 4); return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步