Simplied a DFSBFS with minor modification.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <unordered_set> using namespace std; typedef vector<vector<char>> Matrix; typedef pair<int, int> Pos; bool isWay(Matrix &m, int i, int j) { return m[j][i] == '.' || m[j][i] == '*'; } bool go(Matrix &m, Pos curr, Pos dst, const int k, int n) { if (curr == dst) { return n == k; } int h = m.size(); int w = m[0].size(); int i = curr.first; int j = 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; int nn = 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; } int main() { int n; cin >> n; while (n--) { int h, w; cin >> h >> w; Pos dst, start; Matrix mx(h, vector<char>(w, '.')); for (int j = 0; j < h; j ++) for (int i = 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; } } int k; cin >> k; bool bRet = go(mx, start, dst, k, 0); cout << (bRet ? "Impressed" : "Oops!") << endl; } return 0; }