学霸抢走了大家的作业,班长为了帮同学们找回作业,决定去找学霸决斗。但学霸为了不要别人打扰,住在一个城堡里,城堡外面是一个二维的格子迷宫,要进城堡必须得先通过迷宫。因为班长还有妹子要陪,磨刀不误砍柴功,他为了节约时间,从线人那里搞到了迷宫的地图,准备提前计算最短的路线。可是他现在正向妹子解释这件事情,于是就委托你帮他找一条最短的路线。
第一行两个整数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。
求最短路径可以想到用广度优先搜索,由于输出的必须是字典序最小的一个,所以按照D L R U的顺序进行搜索。
#include<iostream> #include<queue> #include<cstring> using namespace std; const int N = 5e2+5; char mp[N][N]; // 建立迷宫地图 int visit[N][N]; // 标记该点是否走过 int d[4][2] = {{1,0},{0,-1},{0,1},{-1,0}};//方向数组,按照下左右上的顺序 string ds[4] = {"D","L","R","U"}; int n,m; //迷宫的行和列 struct node{ int x; int y; int step; string s; node(int xx,int yy,int steps,string ss) { x = xx; y = yy; step = steps; s = ss; } }; queue<node> q; void bfs(int x,int y) { q.push(node(x,y,0,"")); visit[x][y] = 1; while(!q.empty()) { node now = q.front(); q.pop(); if(now.x == n-1 && now.y == m-1)//如果已到达终点 { cout << now.step << endl; cout << now.s << endl; break; } for(int i = 0; i < 4; ++i)//继续搜索 { int nx = now.x + d[i][0]; int ny = now.y + d[i][1]; if(nx<n && nx>=0 && ny<m && ny>=0 && visit[nx][ny]==0 && mp[nx][ny]=='0') { q.push(node(nx,ny,now.step+1,now.s+ds[i])); visit[nx][ny] = 1; } } } } int main() { cin >> n >> m; for(int i = 0; i < n; ++i) cin >> mp[i]; bfs(0,0); return 0; }