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)
Solution
算一个模版吧。。
AC代码
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
int b[5][5];
int c[101],d[101];
int x[4]={0,0,1,-1},y[4]={1,-1,0,0};
typedef struct node
{
int x,y;
}s;
struct a
{
int qx,qy;
}e[5][5];
void bfs(int i,int j)
{
queue<node>a;
node t;
t.x=i;
t.y=j;
a.push(t);
b[i][j]=1;
while(!a.empty())
{
node s,u;
s=a.front();
a.pop();
for(int k=0;k<4;++k)
{
u.x=s.x+x[k];
u.y=s.y+y[k];
if(u.x>=0&&u.x<=4&&u.y>=0&&u.y<=4&&!b[u.x][u.y])
{
a.push(u);
e[u.x][u.y].qx=s.x;
e[u.x][u.y].qy=s.y;
b[u.x][u.y]=1; //
}
if(u.x==4&&u.y==4) return;
}
}
}
void print(int a,int b)
{
if(a==0&&b==0)
{
printf("(%d, %d)\n",a,b);
return;
}
int c=e[a][b].qx;
int d=e[a][b].qy;
print(c,d);
if(a==4&&b==4) printf("(%d, %d)",a,b);
else printf("(%d, %d)\n",a,b);
}
int main()
{
for(int i=0;i<5;++i)
for(int j=0;j<5;++j)
scanf("%d",&b[i][j]);
bfs(0,0);
print(4,4);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)