In fact, you only need to find one to exit, so the efficiency is not very low. You can directly use DFS to quit.
# Include <iostream> # include <cstdio> # include <algorithm> # include <cstring> # include <cmath> # include <vector> using namespace std; int dx [] = {-,}; int dy [] = {, 1,-1}; vector <char> ans; int n, m; char map [30] [30]; char t [30] [30]; bool found; void copy () // copy the map {for (int I = 0; I <n; I ++) for (int j = 0; j <m; j ++) each time) map [I] [j] = t [I] [j];} void debug (int ax, int ay) // debug the function ~~~ {For (int I = 0; I <n; I ++) {for (int j = 0; j <m; j ++) {if (I = ax & j = ay) {printf ("@"); continue;} printf ("% c ", map [I] [j]);} puts ("");} puts ("");} bool OK (int xx, int yy) {if (xx <n & xx> = 0 & yy <m & yy> = 0) return true; return false;} bool tag () // All bricks are cleared {for (int I = 0; I <n; I ++) for (int j = 0; j <m; j ++) if (map [I] [j]! = '. ') Return false; return true;} bool dfs (int posx, int posy) {if (found) return true; if (tag () {found = true; return true;} // debug (posx, posy); for (int k = 0; k <4; k ++) {if (map [posx + dx [k] [posy + dy [k]! = '.' |! OK (posx + dx [k], posy + dy [k]) continue; for (int I = 1; I <= 25; I ++) {if (map [posx + I * dx [k] [posy + I * dy [k]! = '. '& OK (posx + I * dx [k], posy + I * dy [k]) {int tx = posx + I * dx [k]; int ty = posy + I * dy [k]; char cur1 = map [tx] [ty]; char cur2 = map [tx + dx [k] [ty + dy [k]; map [tx] [ty] = '. '; if (cur1! = 'A') {if (cur2 = '. ') {map [tx + dx [k] [ty + dy [k] = cur1-1; // undo it first} else {map [tx + dx [k] [ty + dy [k] = cur1-'A' + cur2; // if there is something behind it, it must be a combination} if (k = 0) ans. push_back ('U'); else if (k = 1) ans. push_back ('D'); else if (k = 2) ans. push_back ('R'); else ans. push_back ('l'); dfs (tx, ty); if (found) return true; map [tx] [ty] = cur1; map [tx + dx [k] [ty + dy [k] = cur2; ans. pop_back (); break ;}}return false;} int main () {while (scanf ("% D % d ", & m, & n )! = EOF) {found = false; ans. clear (); for (int I = 0; I <n; I ++) scanf ("% s", t [I]); for (int I = 0; I <n; I ++) {for (int j = 0; j <m; j ++) {if (t [I] [j]! = '. ') Continue; copy (); if (dfs (I, j) {printf ("% d \ n", I, j); break ;}} if (found) break;} for (int sb = 0; sb <ans. size (); sb ++) printf ("% c", ans [sb]); puts ("") ;}return 0 ;} /* 13 3 ................ bb .. bc ................. 7 8 ................... B ......... aa. B ....... a ............... */