做了一题简单的迷宫题,但是OJ一直显示“输出超限”,一直找不到哪里出错
后来发现,原来,我的习惯是:先判断合法性、设置标志,再进入下一层DFS,
但是!!!在main函数进入DFS的第一层的时候,我忘记设置“标志”,这就违反了我上面“先标志,后进入”的原则,导致迷宫路径计算出错
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<unordered_map>
#include<string.h>
#include<vector>
#include<queue>
#include<stack>
#include<functional>
#include<cmath>
using namespace std;
typedef long long ll;
int n, m;
int sx, sy, ex, ey;
const int dir[4][2] = { {0,-1},{-1,0},{0,1},{1,0} };
vector<pair<int, int>> path;
int map[20][20];
bool noPath;
void dfs(int x, int y) {
if (x == ex&&y == ey) {
for (int i = 0; i < path.size(); i++) {
printf("(%d,%d)", path[i].first, path[i].second);
if (i != path.size() - 1)printf("->");
}
printf("\n");
noPath = false;
return;
}
int tx, ty;
for (int i = 0; i < 4; i++) {
tx = x + dir[i][0];
ty = y + dir[i][1];
if (tx<1 || tx>m || ty<1 || ty>n)continue;
if (map[tx][ty] == 1) {
map[tx][ty] = 0;
path.push_back(make_pair(tx, ty));
dfs(tx, ty);
path.pop_back();
map[tx][ty] = 1;
}
}
}
int main() {
scanf("%d %d", &m, &n);
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
scanf("%d", &map[i][j]);
scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
map[sx][sy] = 0; //!!!!!!这里之前忘记打标志了!!!!!!!!!!!!
path.clear();
path.push_back(make_pair(sx, sy));
noPath = true;
dfs(sx, sy);
if (noPath)printf("-1\n");
return 0;
}