[蓝桥杯][2016年第七届真题]路径之谜(dfs)

题目描述

小明冒充X星球的骑士,进入了一个奇怪的城堡。

城堡里边什么都没有,只有方形石头铺成的地面。

假设城堡地面是 n x n 个方格。【如图1.png】所示。

按习俗,骑士要从西北角走到东南角。
可以横向或纵向移动,但不能斜着走,也不能跳跃。
每走到一个新方格,就要向正北方和正西方各射一箭。
(城堡的西墙和北墙内各有 n 个靶子)


同一个方格只允许经过一次。但不必走完所有的方格。

如果只给出靶子上箭的数目,你能推断出骑士的行走路线吗?

有时是可以的,比如图1.png中的例子。

本题的要求就是已知箭靶数字,求骑士的行走路径(测试数据保证路径唯一)

输入

第一行一个整数N(0<N<20),表示地面有 N x N 个方格
第二行N个整数,空格分开,表示北边的箭靶上的数字(自西向东)
第三行N个整数,空格分开,表示西边的箭靶上的数字(自北向南)

输出

一行若干个整数,表示骑士路径。

扫描二维码关注公众号,回复: 6071897 查看本文章

为了方便表示,我们约定每个小格子用一个数字代表,从西北角开始编号: 0,1,2,3....
比如,图1.png中的方块编号为:

0  1  2  3
4  5  6  7
8  9  10 11
12 13 14 15

样例输入

4
2 4 3 4
4 3 3 3

样例输出

0 4 5 1 2 3 7 11 10 9 13 14 15

简单搜索

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<cmath>

const int maxn=1e5+5;
typedef long long ll;
using namespace std;
struct node
{
	int x,y;
	int cnt;
};
int vis[25][25];
int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
int row[25];
int cow[25];
int Map[2500];
int n;
int s=0;
int ss=0;
int cnt=0;
void dfs(int x,int y,int step)
{
	vis[x][y]=1;
	
	Map[step]=x*n+y;
	if(x==n-1&&y==n-1&&step==s)
	{
		for(int t=1;t<=step;t++)
		{
			cout<<Map[t]<<" ";
		}
		cout<<endl;
		return;
	}
	if(step>s)
	{
		return;
	}
	for(int t=0;t<n;t++)
	{
		int xx=x+dir[t][0];
		int yy=y+dir[t][1];
		if(xx>=0&&xx<n&&yy>=0&&yy<n&&vis[xx][yy]==0&&row[yy]-1>=0&&cow[xx]-1>=0)
		{
			vis[xx][yy]=1;
			row[yy]--;
	        cow[xx]--;
			dfs(xx,yy,step+1);
			vis[xx][yy]=0;
			row[yy]++;
			cow[xx]++;
		}
	}
}
int main()
{
	
	cin>>n;
	for(int t=0;t<n;t++)
	{
		cin>>row[t];
		s+=row[t];
	}
	for(int t=0;t<n;t++)
	{
		cin>>cow[t];
	}
	dfs(0,0,1);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lbperfect123/article/details/89469189