hdu 2821 DFS

来源:互联网 发布:网络彩票平台排名 编辑:程序博客网 时间:2024/05/21 15:56

英语渣的伤悲,刚开始没看清题就开始做了,然后WA了好多次,这题要注意的是推箱子。。。推。。。推。。。。刚开始我傻逼了。。。模拟的过程木有推啊啊啊啊

不说了,直接上代码:

AC代码如下:

#include <iostream>#include <cstdio>#include <cstring>#include <string>using namespace std;typedef struct{int x, y;}Point;int N, M;int map[25][25];int now[25][25];int moves[][2] = { -1, 0, 0, 1, 1, 0, 0, -1 };int Sum;string dir[4] = { "U", "R", "D", "L" };string ans;//判断在p点能不能从direction方向走bool judgeahead( Point p, int direction ){if( now[p.x][p.y] ){return false;}Point arround;arround.x = p.x + moves[direction][0];arround.y = p.y + moves[direction][1];if( now[arround.x][arround.y] ){return false;}for( int i = 2; ; i++ ){arround.x = p.x + moves[direction][0] * i;arround.y = p.y + moves[direction][1] * i;if( arround.x < 0 || arround.y < 0 || arround.x >= N || arround.y >= M ){return false;}if( now[arround.x][arround.y] ){return true;}}}bool DFS( Point p, string prev, int prevnum ){if( prevnum >= Sum ){ans = prev;return true;}for( int i = 0; i < 4; i++ ){if( judgeahead( p, i ) ){Point newp;for( int l = 2; ; l++ ){newp.x = p.x + moves[i][0] * l;newp.y = p.y + moves[i][1] * l;if( now[newp.x][newp.y] ){break;}}Point ppp = newp;ppp.x += moves[i][0];ppp.y += moves[i][1];if( ppp.x < 0 || ppp.y < 0 || ppp.x >= N || ppp.y >= M ){//箱子不能被推出去continue;;}int a = now[ppp.x][ppp.y];int b = now[newp.x][newp.y];string sss = "";sss += dir[i];now[newp.x][newp.y] = 0;//推箱子now[ppp.x][ppp.y] = a + b - 1;if( DFS( newp, prev + dir[i] , prevnum + 1 ) ){return true;}now[ppp.x][ppp.y] = a;//箱子复原now[newp.x][newp.y] = b;}}return false;}int main(){char s[26];while( scanf( "%d%d", &M, &N ) != EOF ){Sum = 0;ans = "";int ansi, ansj;for( int i = 0; i < N; i++ ){scanf( "%s", s );for( int j = 0; j < M; j++ ){if( s[j] == '.' ){map[i][j] = 0;}else{map[i][j] = s[j] - 'a' + 1;Sum += map[i][j];}}}bool flag = false;for( int i = 0; i < N && !flag; i++ ){//遍历初始位置for( int j = 0; j < M && !flag; j++ ){Point p;p.x = i;p.y = j;for( int ii = 0; ii < N; ii++ ){for( int jj = 0; jj < M; jj++ ){now[ii][jj] = map[ii][jj];}}for( int k = 0; k < 4; k++ ){//本来想把初始位置压入DFS过程的,但不知道怎么弄就直接在这写了if( judgeahead( p, k ) ){Point newp;for( int l = 2; ; l++ ){newp.x = p.x + moves[k][0] * l;newp.y = p.y + moves[k][1] * l;if( now[newp.x][newp.y] ){break;}}Point ppp = newp;ppp.x += moves[k][0];ppp.y += moves[k][1];if( ppp.x < 0 || ppp.y < 0 || ppp.x >= N || ppp.y >= M ){//箱子不能被推出去continue;;}int a = now[ppp.x][ppp.y];int b = now[newp.x][newp.y];string sss = "";sss += dir[k];now[newp.x][newp.y] = 0;now[ppp.x][ppp.y] = a + b - 1;if( DFS( newp, sss , 1 ) ){ansi = i;ansj = j;flag = true;break;}now[ppp.x][ppp.y] = a;now[newp.x][newp.y] = b;}}}}cout << ansi << endl;cout << ansj << endl;cout << ans << endl;}return 0;}