Problem description Genius robbed everyone's homework, monitor to help students find homework, decided to find genius duel. But genius in order not to disturb others, live in a castle, outside the castle is a two-dimensional lattice maze, to enter the castle must first through the maze. Because the squad leader and sister to accompany, sharpening not mistakenly chopping wood work, he to save time, from the line people got a maze map, ready to calculate the shortest route ahead. But now he is explaining the matter to his sister, so he will entrust you to find the shortest route for him. Input format the first line two integers n, m, for the length and width of the maze.
The next n lines, the number of m in each line, are not spaced between 0 or 1. 0 means that the lattice can pass, and 1 means no. Suppose you are now in the labyrinth coordinates (in the upper-left corner of the maze), the exit of the Maze (n,m). Each move can only be moved up and down in 4 directions to another pass through the grid, each move to calculate one step. Data Assurance (N,M) can be passed. Output format the first line one number is the minimum number of steps required K.
The second line is k characters, each character ∈{u,d,l,r}, respectively, indicating the upper and lower sides. If there are multiple shortest paths of the same length, select the one with the smallest dictionary order under this representation method. Sample inputs Input Sample 1:
3 3
001
100
110
Input Sample 2:
3 3
000
000
000 Sample outputs Output sample 1:
4
Rdrd
Output Sample 2:
4
DDRR data size and conventions have 20% data to meet: 1<=n,m<=10
There are 50% data to meet: 1<=n,m<=50
There are 100% of data to meet: 1<=n,m<=500.
A simple wide search topic, for me to find the shortest short-circuit is not too difficult, but the path of the record is a bit difficult.
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>#defineN 550using namespacestd;structnode{intx, y; intnum;};intN, M;CharMap[n][n];intVis[n][n];intdir[4][2] = {1,0,0, -1,0,1, -1,0};intPre[n][n];Charstr[5] = {"Dlru"};BOOLCheckintXinty) { if(x<1|| x>n| | y<1|| Y>m)return false; return 1;}voidBFs () {Queue<node>Q; Node St; St.x=1, St.y =1, St.num =0; Q.push (ST); vis[1][1] =1; pre[1][1] = -1; while(!Q.empty ()) {St=Q.front (); Q.pop (); if(St.x = = N && st.y = =m) {printf ("%d\n", St.num); return ; } intI, J; Node Ed; for(i =0; I <4; i++) {ed.x= St.x + dir[i][0]; Ed.y= St.y + dir[i][1]; Ed.num= St.num +1; if(Check (ED.X,ED.Y) && map[ed.x][ed.y] = ='0'&&!Vis[ed.x][ed.y]) {PRE[ED.X][ED.Y]=i; Q.push (ed); VIS[ED.X][ED.Y]=1; } } }}voidPathintXinty) { if(x = =1&& y = =1)return; Path (x-dir[pre[x][y]][0], y-dir[pre[x][y]][1]); printf ("%c", Str[pre[x][y]]);}intMain () {scanf ("%d%d", &n, &m); intI, J; for(i =1; I <= N; i++) { for(j =1; J <= M; J + +) {scanf ("%c", &Map[i][j]); } getchar (); } BFS (); Path (n, m); return 0;}
View Code
Algorithm to improve the maze of genius