1220.Look for homework -山师oj

版权声明:只要我还活着,我就要凿穿codeforces. https://blog.csdn.net/UnKfrozen/article/details/85053880

1220.Look for homework

1220.Look for homework

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

  The input consists several cases.For each case starts with two integers n,m(2<=n,m<=102<=n,m<=10),symbolizing the length and width of the maze.The next n lines contain m numbers with no space and value for only 0 and 1.The essence is that 0 can pass ,1 can’t pass. Now you are in the place of (1,1) refering to the top left corner.the export is in the place of (n,m).Each step can only walk with up,down,left and right.

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

解析

搜索水题,注意是按照U,D,L,R的顺序搜索就可以了

#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<queue>
#include<stdio.h>
#include<stdlib.h>
#include<map>
#ifndef NULL
#define NULL 0
#endif
using namespace std;

struct vec {
	int x, y,t;
	char s[1000] = { 0 };
}p;
int n, m,dx[] = { -1,1,0,0 }, dy[] = { 0,0,1,-1 };
char mp[11][11], sx[] = { 'U','D','R','L' };
int main()
{
	while (cin >> n >> m) {
		for (int i = 0; i < n; i++)
			cin >> mp[i];
		queue<vec>q;
		q.push(p);
		while (!q.empty()) {
			vec k = q.front();q.pop();
			if (k.x == n - 1 && k.y == m - 1) {
				cout <<k.t<<endl<< k.s+1 << endl;
				break;
			}
			for (int i = 0; i < 4; i++) {
				vec ip = k;
				int ix = k.x + dx[i], iy = k.y + dy[i],t=k.t+1;
				if (ix >= 0 && ix < n&&iy >= 0 && iy < m && mp[ix][iy] != '1') {
					mp[ix][iy] = '1';
					k.x = ix,k.y=iy,k.t=t,k.s[t] = sx[i];
					q.push(k);
					k = ip;
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/UnKfrozen/article/details/85053880