路径之谜
小明冒充X星球的骑士,进入了一个奇怪的城堡。
城堡里边什么都没有,只有方形石头铺成的地面。
假设城堡地面是 n x n 个方格。【如图1.png】所示。
按习俗,骑士要从西北角走到东南角。
可以横向或纵向移动,但不能斜着走,也不能跳跃。
每走到一个新方格,就要向正北方和正西方各射一箭。
(城堡的西墙和北墙内各有 n 个靶子)
同一个方格只允许经过一次。但不必做完所有的方格。
如果只给出靶子上箭的数目,你能推断出骑士的行走路线吗?
有时是可以的,比如图1.png中的例子。
本题的要求就是已知箭靶数字,求骑士的行走路径(测试数据保证路径唯一)
输入:
第一行一个整数N(0< N<20),表示地面有 N x N 个方格
第二行N个整数,空格分开,表示北边的箭靶上的数字(自西向东)
第三行N个整数,空格分开,表示西边的箭靶上的数字(自北向南)
输出:
一行若干个整数,表示骑士路径。
为了方便表示,我们约定每个小格子用一个数字代表,从西北角开始编号: 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
资源约定:
峰值内存消耗 < 256M
CPU消耗 < 1000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意: main函数需要返回0
注意: 只使用ANSI C/ANSI C++ 标准,不要调用依赖于编译环境或操作系统的特殊函数。
注意: 所有依赖的函数必须明确地在源文件中 #include , 不能通过工程设置而省略常用头文件。
提交时,注意选择所期望的编译器类型。
——————————这是萌萌哒的分割线,萌不萌???不萌不给看代码——————————-
这一次的注释写的还算清楚 ,,
小弟水平有限,思路粗糙,有更好的方法思路,望不吝赐教,谢过各位大神,(跑路)
#include<stdio.h>
#include<string.h>
int exiting[404]={0}; //已走路径
int north[21]; //北靶子
int west[21]; //西靶子
int path[404]; //路径
int N;
int path_index=1; //路径下标
int left_move(int current)
{
return current-1;
}
int right_move(int current)
{
return current+1;
}
int up_move(int current)
{
return current-N;
}
int down_move(int current)
{
return current+N;
}
int (* step[])(int )={left_move,right_move,up_move,down_move};
int is_end(int current)
{
if(current==N*N-1&&north[N-1]==0&&west[N-1]==0)
return 1;
return 0;
}
//int last_current=0;
int is_legal(int current)
{
if(north[current%N]-1>=0&&west[current/N]-1>=0)
return 1;
return 0;
}
int ok=0;
void calculate(int current)
{
if(is_end(current))
{
ok=1;
return; //结束
}
for(int i=0;i<4;i++)
{
int current_temp=current;
if(current<N&&i==2) continue; //第一行不能上移
if(current>N*(N-1)-1&&i==3) continue; //最后一行不能下移
if(current%N==0&&i==0) continue; //第一列不能左移
if(current%(N-1)==0&&i==1) continue; //最后一列不能右移
current_temp=step[i](current); //移动
// printf("cur %d cur_temp %d \n",current,current_temp);
if(exiting[current_temp]==1) continue; //走了回头路
if(!is_legal(current_temp)) continue; //超过靶子上的数
exiting[current_temp]=1; //标记已走
path[path_index++]=current_temp; //存入路径
north[current_temp%N]-=1; //箭数减一
west[current_temp/N]-=1; //同上
calculate(current_temp); //下一步
if(ok) return; //结束
exiting[current_temp]=0;
path_index--;
north[current_temp%N]+=1;
west[current_temp/N]+=1;
}
}
void show(int path[])
{
printf("\n");
for(int i=0;i<path_index;i++)
{
printf("%d ",path[i]);
}
}
int main()
{
scanf("%d",&N);
for(int i=0;i<N;i++)
{
scanf("%d",&north[i]);
}
for(int i=0;i<N;i++)
{
scanf("%d",&west[i]);
}
path[0]=0;
north[0]-=1;
west[0]-=1;
path[N*N-1]=N*N-1;
calculate(0);
show(path);
return 0;
}