SDNU 1220.Look for homework(BFS路径标记)
Description
(the picture has no relation with this problem..I just want to add a picture. emmm..)
Super scholar robs the all homework of others. The monitor decides to combat with the super scholar so as to help students to get back the homework. But super scholar lives in a castle because he doesn't want to be disturbed. The outside of the castle is a maze with two dimension grids. Entering the castle must pass the maze. The monitor needs to save time because of accompanying his girlfriend, so he wants to make a student named Huachao Wei help him who hasn't a girlfriend. Now he has the map of the maze and needs to calculate the shortest path.
Input
Output
For each case,the first line prints the least number of steps to arrive the castle.The second line prints k characters for U,D,L,R,representing up,down,left,right.if there are many paths with the same length,please print the path with Minimum dictionary.It is guarantees that there must have a path for arriving the castle.
Sample Input
3 3 001 100 110 3 3 000 000 000
Sample Output
4 RDRD 4 DDRR
Source
Unknown
思路:真是道神奇的题啊。读入数据不可以直接用int型;在走上下左右的时候,题目说要按字典序最小输出,于是对于走的先后就有了区分:要下、左、右、上依次走,才能符合题目的要求。
#include <cstdio> #include <iostream> #include <cmath> #include <string> #include <cstring> #include <algorithm> #include <queue> #include <vector> #include <map> using namespace std; #define ll long long int n, m, position[18][18]; int path[4][2] = {1,0, 0,-1, 0,1, -1,0}; struct node { int x, y; }; struct edge { int x, y, s = 0; char step; } e[100+8][100+8]; void bfs() { queue<node>q; node p; p.x = 0; p.y = 0; position[0][0] = 1; q.push(p); while(!q.empty()) { node l = q.front(); q.pop(); if(l.x == n-1 && l.y == m-1)return; for(int i = 0; i<4; i++) { node w; w.x = l.x+path[i][0]; w.y = l.y+path[i][1]; if(w.x>=0 && w.y>=0 && w.x < n && w.y < m && !position[w.x][w.y]) { position[w.x][w.y] = 1; e[w.x][w.y].s = e[l.x][l.y].s+1; e[w.x][w.y].x = l.x;//记录该点的上一个点,因为上一个点是确认的 e[w.x][w.y].y = l.y;//记录该点的上一个点,因为上一个点是确认的 if(i == 0)e[w.x][w.y].step = 'D'; else if(i == 1)e[w.x][w.y].step = 'L'; else if(i == 2)e[w.x][w.y].step = 'R'; else if(i == 3)e[w.x][w.y].step = 'U'; q.push(w); } } } } void print(int a, int b) { if(a == 0 && b == 0)return; print(e[a][b].x, e[a][b].y); printf("%c", e[a][b].step); } int main() { while(~scanf("%d%d", &n, &m)) { char s[18][18]; for(int i = 0; i < n; i++)scanf("%s", s[i]); for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { if(s[i][j] == '0')position[i][j] = 0; else position[i][j] = 1; } bfs(); printf("%d\n", e[n-1][m-1].s); print(n-1, m-1); printf("\n"); } return 0; }