Simplied a dfs\bfs with minor modification.
#include <cmath>#include<cstdio>#include<vector>#include<iostream>#include<algorithm>#include<unordered_set>using namespacestd;typedef Vector<vector<Char>>Matrix;typedef pair<int,int>Pos;BOOLIsway (Matrix &m,intIintj) { returnM[j][i] = ='.'|| M[j][i] = ='*';}BOOLGo (Matrix &m, pos curr, POS DST,Const intKintN) { if(Curr = =DST) { returnn = =K; } inth =m.size (); intW = m[0].size (); inti =Curr.first; intj =Curr.second; Vector<Pos>Cands; if(I >0&& Isway (M, I-1, J)) {Cands.push_back (Pos (i-1, J)); } if(I < W-1&& Isway (m, i +1, J)) {Cands.push_back (Pos (i+1, J)); } if(J >0&& Isway (M, I, J-1) {Cands.push_back (Pos (i, J )-1)); } if(J < H-1&& Isway (M, I, J +1) {Cands.push_back (Pos (i, J )+1)); } if(cands.size () = =0)return false; intnn = cands.size () >1? (n +1): N; for(Auto &r:cands) {M[r.second][r.first]='X'; if(Go (M, R, DST, K, nn)) {return true; } } return false;}intMain () {intN CIN >>N; while(n--) { intH, W; Cin >> H >>W; Pos DST, start; Matrix mx (h, Vector<Char> (W,'.')); for(intj =0; J < H; J + +) for(inti =0; i < W; i++) {cin>>Mx[j][i]; Switch(Mx[j][i]) { Case 'M': Start.first=i; Start.second=J; Break; Case '*': Dst.first=i; Dst.second=J; Break; } } intK CIN >>K; BOOLBRet = Go (MX, start, DST, K,0); cout<< (BRet?"impressed":"oops!") <<Endl; } return 0;}
Hackerrank-count Luck