HDU2821 深搜 xingxing1024
这道题就是按照题意搜索就行, 也没啥坑的地方,代码如下:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int n, m; //n行 m列 int map[26][26]; char line[30]; char dir[4] = {'R', 'L', 'D', 'U'}; int dx[] = {0, 0, 1, -1}; int dy[] = {1, -1, 0, 0}; bool inside(int x, int y) { return (x>=0 && x<n && y>=0 && y<m); } int now[26][26]; int judge() { for(int i=0; i<n; i++) for(int j=0; j<m; j++) if(now[i][j] > 0) return false; return true; } int go[1000], ss; bool flog; void dfs(int x, int y, int steps) //走到x, y走了 steps步 { //printf("x = %d, y=%d, steps = %d\n", x, y, steps); if(judge()) { ss = steps; flog = true; } else { for(int i=0; i<4&&!flog; i++) //朝四个方向走 { int nx = x, ny=y; while(inside(nx+dx[i], ny+dy[i]) && now[nx+dx[i]][ny+dy[i]]==0) nx = nx+dx[i], ny = ny+dy[i]; if(!inside(nx+dx[i], ny+dy[i])) continue; else if(now[nx+dx[i]][ny+dy[i]]>0 && nx==x && ny==y) continue; else if(now[nx+dx[i]][ny+dy[i]]>0 && (nx!=x || ny!=y)) { go[steps] = i; int num = now[nx+dx[i]][ny+dy[i]]; if(inside(nx+2*dx[i], ny+2*dy[i])) now[nx+2*dx[i]][ny+2*dy[i]] += (now[nx+dx[i]][ny+dy[i]]-1); now[nx+dx[i]][ny+dy[i]] = 0; dfs(nx+dx[i], ny+dy[i], steps+1); now[nx+dx[i]][ny+dy[i]] = num; if(inside(nx+2*dx[i], ny+2*dy[i])) now[nx+2*dx[i]][ny+2*dy[i]] -= (now[nx+dx[i]][ny+dy[i]]-1); } } } } int main() { while(scanf("%d%d", &m, &n) == 2) { for(int i=0; i<n; i++) { scanf("%s", line); for(int j=0; j<m; j++) { if(line[j] == '.') map[i][j] = 0; else map[i][j] = line[j]-'a'+1; } } /* for(int i=0; i<n; i++) { for(int j=0; j<m; j++) printf("%d ", map[i][j]); printf("\n"); }*/ bool co = false; int tpx, tpy; for(int i=0; i<n&&!co; i++) for(int j=0; j<m&&!co; j++) { if(map[i][j]>0) continue; //printf("sx = %d, sy = %d\n\n", i, j); memcpy(now, map, sizeof(map)); flog = false; dfs(i, j, 0); if(flog == true) { co = true; tpx = i; tpy = j; } } printf("%d\n%d\n", tpx, tpy); for(int i=0; i<ss; i++) printf("%c", dir[go[i]]); printf("\n"); } return 0; }