迷宫问题输出超限反思

 做了一题简单的迷宫题,但是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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值