代码还可以优化吗?
  • 板块灌水区
  • 楼主Wendy_Hello_qwq
  • 当前回复13
  • 已保存回复13
  • 发布时间2024/5/9 20:16
  • 上次更新2024/5/9 21:56:38
查看原帖
代码还可以优化吗?
1039211
Wendy_Hello_qwq楼主2024/5/9 20:16

原题戳这里

#include <cstdio>
using namespace std;
bool vis[7][7];
int n, m, t, sx, sy, fx, fy, ans, p, q;
// 走迷宫的四个方向 
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void dfs (int, int);
int main()
{
	scanf ("%d%d%d", &n, &m, &t);
	scanf ("%d%d%d%d", &sx, &sy, &fx, &fy);
	// 对起点进行标记 
	vis[sx][sy] = 1;
	// 输入t组障碍坐标数据 
	for (int i = 1; i <= t; i++)
	{
		scanf ("%d%d", &p, &q);
		// 对障碍的坐标进行标记 
		vis[p][q] = 1;
	}
	// 从起点开始深搜 
	dfs (sx, sy);
	// 输出方案数 
	printf ("%d", ans);
	return 0;
}
void dfs (int x, int y)
{
	// 当x坐标和y坐标到达了终点的坐标时 
	if (x == fx && y == fy)
	{
		// 方案数加1 
		ans++;
		// 返回上一步 
		return;
	}
	else
	{
		// 循环三个方向,循环从0开始,因为数组定义也从0开始 
		for (int i = 0; i <= 3; i++)
		{
			// 定义新的x坐标,它是原来的x坐标加上当前的行走的方向 
			int xx = x + dx[i];
			// 定义新的y坐标,它是原来的y坐标加上当前的行走的方向 
			int yy = y + dy[i];
			// 判断是否出界以及当前点是否能走 
			if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && vis[xx][yy] == 0)
			{
				// 对当前点进行标记 
				vis[xx][yy] = 1;
				dfs (xx, yy);
				// 回溯,取消对当前点的标记 
				vis[xx][yy] = 0;
			}
		}
	}
}
2024/5/9 20:16
加载中...