社区讨论

10分求调(玄关)

P1238走迷宫参与者 2已保存回复 1

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
1 条
当前快照
1 份
快照标识符
@lvi30wa7
此快照首次捕获于
2024/04/27 20:32
2 年前
此快照最后确认于
2024/04/27 22:01
2 年前
查看原帖
CPP
#include <iostream>
#include <vector>

using namespace std;

int n, m;
int sx, sy, ex, ey, ans;
int a[15 + 5][15 + 5], mp[15 + 5][15 + 5];
int x_[5] = {0, -1, 0, 1};
int y_[5] = {-1, 0, 1, 0};

struct node
{
	int x, y;
};
vector<node> res;

void print()
{
	for(int i = 0; i < res.size() - 1; i++)
	{
		cout << "(" << res[i].x << "," << res[i].y << ")" << "->";
	}
	cout << "(" << res.back().x << "," << res.back().y << ")" << endl; //最后没有“->”,单独输出
}

void dfs(int x1, int x2, int y1, int y2, int m, int n)
{
	if(x1 == x2 && y1 == y2) //到终点了
	{
		ans++;
		print();
		return ;
	}

	for(int i = 0; i < 4; i++)
	{
		int dx = x1 + x_[i];
		int dy = y1 + y_[i];
		if(mp[dx][dy] != 1 /*没有障碍*/  && dx <= m && dy <= n && dx >= 1 && dy >= 1 /*没有越界*/ && a[dx][dy] != 1 /*没有经过*/)
		{
			a[dx][dy] = 1; //标记为经过
			res.push_back({dx, dy}); //把当前的x和y存入res
			dfs(dx, dy, x2, y2, m, n); //继续搜索
			a[dx][dy] = 0;
			res.pop_back();
		}
	}
}

signed main()
{

	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);// 关闭同步流

	cin >> m >> n;
	for(int i = 1; i <= m; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			cin >> a[i][j];
		}
	}
	cin >> sx >> sy;
	cin >> ex >> ey;

	res.push_back({sx, sy}); //最开始已经来过了(标记起点)
	a[sx][sy] = 1;


	for(int i = 1; i <= m; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			if(a[i][j] == 0)
			{
				mp[i][j] = 1;
			}
		}
	}

	dfs(sx, ex, sy, ey, m, n);

	if(ans == 0) cout << "-1" << endl;

	return 0;
}

回复

1 条回复,欢迎继续交流。

正在加载回复...