#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool hasPath(vector< vector<int> > &res, vector< vector<int> > &vec,int n,int m, int row, int col, int P) {
if (row == 0 && col == m - 1 && P >= 0) {
return true;
}
bool canArrive = false;
if (row >= 0 && row < n && col >= 0 && col < m && vec[row][col] == 1 && P >= 0) {
res.push_back({ row,col });
canArrive = hasPath(res, vec, n, m, row - 1, col, P - 3) ||
hasPath(res, vec, n, m, row + 1, col, P) ||
hasPath(res, vec, n, m, row, col - 1, P - 1) ||
hasPath(res, vec, n, m, row, col + 1, P - 1);
if (!canArrive) {
res.pop_back();
}
}
return canArrive;
}
int main() {
int n, m, P;
while (cin >> n >> m >> P) {
vector<vector<int>> vec(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> vec[i][j];
}
}
vector<vector<int>> res;
bool canArrive = hasPath(res, vec, n, m, 0, 0, P);
if (canArrive) {
int i = 0;
for (; i < res.size() - 1; i++)
{
cout << "[" << res[i][0] << "," << res[i][1] << "]" << ",";
}
cout << "[" << res[i][0] << "," << res[i][1] << "]" << "\n";
}
else
cout << "Can not escape!" << "\n";
}
return 0;
} 提示我运行超时,可能是循环太多,然后通过率50%
我把输出结果改用string来存,不用vector,最后直接输出string,还是不行,一样的提示。
我感觉没啥问题啊...