离了个大谱,有两个点没过
查看原帖
离了个大谱,有两个点没过
1229013
Mr_LiuXinan楼主2024/5/12 16:39

我在调试的时候发现它存在乱走的情况,不知道为什么。 代码如下

#include <iostream>
using namespace std;

int n, tx, ty, sx, sy, zx, zy, minn = 0x7fffffff;
int arr[105][105], book[105][105];
int dir[4][2] = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}};

void dfs(int x, int y, int step)
{
	if (x == zx && y == zy)
	{
		minn = min(step, minn);
		return;
	}
	if (step > minn) return;
	for (int i = 0; i < 4; ++i)
	{
		tx = x + dir[i][0];
		ty = y + dir[i][1];
		if (tx > n || tx < 1 || ty > n || ty < 1)
			continue;
		if (arr[x][y] == arr[tx][ty] || book[tx][ty])
			continue;
		book[tx][ty] = 1;
		dfs(tx, ty, step + 1);
		book[tx][ty] = 0;
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> n;

	char tc;
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= n; ++j)
		{
			cin >> tc;
			if (tc == '-')
				arr[i][j] = 0;
			else if (tc == '+')
				arr[i][j] = 1;
			else if (tc == 'A')
				sx = i, sy = j, arr[i][j] = -1;
			else if (tc == 'B')
				zx = i, zy = j, arr[i][j] = -1;
		}
	}
	book[sx][sy] = 1;
	dfs(sx, sy, 0);

	if (minn == 0x7fffffff)
		cout << -1;
	else
		cout << minn;
	return 0;
}
2024/5/12 16:39
加载中...