P8642 [蓝桥杯 2016 国 AC] 路径之谜

链接

https://www.luogu.com.cn/problem/P8642

思路

dfs,每次到某个节点对统计数组加1.最后与判断数组比。注意剪枝。

代码

#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define int long long
#define itn long long
#define tin long long
#define ll long long
const int mod = 1e9 + 7;

const int N = 30;
int mp[N][N];
int n;
int nums[2][N];
int times[2][N];
bool vis[N][N];
deque<int>dq;
int delta[][2] = { {-1,0},{1,0},{0,1},{0,-1} };

void dfs(int x,int y)
{
	vis[x][y] = 1;
	times[0][y]++;
	times[1][x]++;
	dq.push_back(x * n + y);
	if (x == n - 1 and y == n - 1)
	{
		for(itn i=0;i<2;i++)
			for (int j = 0; j < n; j++)
			{
				if (nums[i][j] != times[i][j])
				{
					dq.pop_back();
					times[0][y]--;
					times[1][x]--;
					vis[x][y] = 0;
					return;
				}
			}
		while (!dq.empty())
		{
			cout << dq.front() << ' ';
			dq.pop_front();
		}
		exit(0);
	}
	for (itn i = 0; i < 2; i++)
		for (int j = 0; j < n; j++)
		{
			if (nums[i][j] < times[i][j])
			{
				dq.pop_back();
				times[0][y]--;
				times[1][x]--;
				vis[x][y] = 0;
				return;
			}
		}
	for (int i = 0; i < 4; i++)
	{
		itn dx = x + delta[i][0], dy = y + delta[i][1];
		if (dx >= 0 and dx < n and dy >= 0 and dy < n and !vis[dx][dy])
		{
			dfs(dx, dy);
		}
	}
	dq.pop_back();
	times[0][y]--;
	times[1][x]--;
	vis[x][y] = 0;
}
void solve()
{
	cin >> n;
	for (int i = 0; i < 2; i++)
		for (int j = 0; j < n; j++)
			cin >> nums[i][j];
	dfs(0, 0);
}

signed main()
{
	IOS;
	solve();
	return 0;
}





posted @ 2025-04-11 14:40  WHUStar  阅读(12)  评论(0)    收藏  举报