您的位置:首页 > 其它

算法提高 学霸的迷宫 蓝桥杯训练

2017-04-06 22:41 267 查看
如有错误欢迎大神指出!!

 算法提高 学霸的迷宫  

时间限制:1.0s   内存限制:256.0MB
    

问题描述

  学霸抢走了大家的作业,班长为了帮同学们找回作业,决定去找学霸决斗。但学霸为了不要别人打扰,住在一个城堡里,城堡外面是一个二维的格子迷宫,要进城堡必须得先通过迷宫。因为班长还有妹子要陪,磨刀不误砍柴功,他为了节约时间,从线人那里搞到了迷宫的地图,准备提前计算最短的路线。可是他现在正向妹子解释这件事情,于是就委托你帮他找一条最短的路线。

输入格式

  第一行两个整数n, m,为迷宫的长宽。

  接下来n行,每行m个数,数之间没有间隔,为0或1中的一个。0表示这个格子可以通过,1表示不可以。假设你现在已经在迷宫坐标(1,1)的地方,即左上角,迷宫的出口在(n,m)。每次移动时只能向上下左右4个方向移动到另外一个可以通过的格子里,每次移动算一步。数据保证(1,1),(n,m)可以通过。

输出格式

  第一行一个数为需要的最少步数K。

  第二行K个字符,每个字符∈{U,D,L,R},分别表示上下左右。如果有多条长度相同的最短路径,选择在此表示方法下字典序最小的一个。

样例输入

Input Sample 1:

3 3

001

100

110

Input Sample 2:

3 3

000

000

000

样例输出

Output Sample 1:

4

RDRD

Output Sample 2:

4

DDRR

数据规模和约定

  有20%的数据满足:1<=n,m<=10

  有50%的数据满足:1<=n,m<=50

  有100%的数据满足:1<=n,m<=500。

中文题目,就不解释了。

题解:一道简单的bfs的题目,有个考点估计就是记录走的顺序并且多条选择要选择字典序小的。

跟杭电有道题目感觉类似。

ac code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <iterator>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <cctype>
using namespace std;

#define si1(a) scanf("%d",&a)
#define si2(a,b) scanf("%d%d",&a,&b)
#define sd1(a) scanf("%lf",&a)
#define sd2(a,b) scanf("%lf%lf",&a,&b)
#define ss1(s) scanf("%s",s)
#define pi1(a) printf("%d\n",a)
#define pi2(a,b) printf("%d %d\n",a,b)
#define mset(a,b) memset(a,b,sizeof(a))
#define forb(i,a,b) for(int i=a;i<b;i++)
#define ford(i,a,b) for(int i=a;i<=b;i++)

typedef long long LL;
const int N=1100001;
const int M=6666666;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-7;
char pla[505][505];
bool vis[505][505];
int fangxiang[4][2]={{1,0},{0,-1},{0,1},{-1,0}};//顺序下,左,右,上,保证字典序最小
struct node
{
int x,y;
int step;
char zoufa[2500];//之前数组开小了,运行错误… 记录走的顺序
}now,next;
int n,m;
void bfs()//基本的bfs模板
{
queue<node > q;
now.x=1,now.y=1;
q.push(now);
vis[now.x][now.y]=1;
now.step=0;
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0;i<4;i++)
{
next=now;
next.x=now.x+fangxiang[i][0];
next.y=now.y+fangxiang[i][1];
if(!vis[next.x][next.y]&&pla[next.x][next.y]=='0')
{
next.step=now.step+1;
vis[next.x][next.y]=1;
if(fangxiang[i][0]==1&&fangxiang[i][1]==0)
{
next.zoufa[now.step]='D';
}
else if(fangxiang[i][0]==-1&&fangxiang[i][1]==0)
{
next.zoufa[now.step]='U';
}
else if(fangxiang[i][0]==0&&fangxiang[i][1]==1)
{
next.zoufa[now.step]='R';
}
else
{
next.zoufa[now.step]='L';
}
if(next.x==n&&next.y==m)
{
return ;
}
else
{
q.push(next);
}
}
}
}
}

int main()
{
si2(n,m);
for(int i=1;i<=n;i++)
{
scanf("%s",pla[i]+1);
}
bfs();
printf("%d\n%s\n",next.step,next.zoufa);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: