学霸的迷宫 ----最短路径---广搜

 学霸的迷宫  
时间限制: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。

终于学会打印路径了 哭 哭数组里的父亲元素是打印路径的关键
此题输入格式中 数据之间没有空格,可以用 %1d 输入,也可以用字符输入
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <list>
#include <algorithm>
#include <cmath>
#include <string>
#include <queue>
using namespace std;
/*
3 3
000
000
000
3 3
001
100
110
3 3
0 0 0
0 0 0
0 0 0
*/
typedef struct queue{
	int x;
	int y;
	int step;
	int f;
	int lujing;
}que;
int n,m;
int a[510][510];
int book[510][510];
que q[2510];
int head,tail;
int luj[2510];
void bfs(){
	int flag = 0;
	int tx,ty;
	int next[4][3] = { {-1,0,1},
	                   {1,0,2},
	                   {0,-1,3},
	                   {0,1,4}
	                 };
	
	book[1][1] = 1;
	head = 1;
	tail = 1;
	q[tail].x = 1;
	q[tail].y = 1;
	q[tail].step = 0;
	q[tail].f = -1;
	tail++;
	while(head < tail){
		for(int i = 0; i <= 3; ++i){
			tx = q[head].x + next[i][0];
			ty = q[head].y + next[i][1];
			if(tx > n || ty > m || tx < 1 || ty < 1) continue;
			if(book[tx][ty] == 0 && a[tx][ty] == 0){
				book[tx][ty] = 1;
				q[tail].x = tx;
				q[tail].y = ty;
				q[tail].step = (q[head].step + 1);
				q[tail].f = head;
				q[tail].lujing = next[i][2];
				tail++;
			}
			if(tx == n && ty == m){
				flag = 1;
				break;
			}
		}
		if(flag) break;
		head++;
	}
}
void print(){
	int i,j;
	i = tail - 1;
	j = 0;
	while(q[i].f != -1){
		luj[++j] = q[i].lujing;
		i = q[i].f;
	}
	for(int k = j; k >= 1; --k){
		if(luj[k] == 1) printf("U");
		else if(luj[k] == 2) printf("D");
		else if(luj[k] == 3) printf("L");
		else if(luj[k] == 4) printf("R");
	}
	printf("\n");
}
int main(int argc, char *argv[]) {
	memset(book,0,sizeof(book));
	scanf("%d%d",&n,&m);
	getchar();
	for(int i = 1; i <= n; ++i){
		for(int j = 1; j <= m; ++j){
			scanf("%1d",&a[i][j]);
		}
		getchar();
	}
	bfs();
	printf("%d\n",q[tail-1].step);
	print();
	return 0;
}


猜你喜欢

转载自blog.csdn.net/shengsikandan/article/details/50897903
今日推荐