小明冒充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
思路:dfs+记录路径
题目比较简单,其中需要注意的就是在中间进行dfs的时候,需要将位置原来换掉的情况重新换回来,比如开始的时候是将一个坐标设置成为已访问,dfs之后就需要将这个位置重新设置成未访问,另外就是在dfs之前将两个方位的数字减一,之后在dfs之后需要再将数据进行恢复。
package 第七届C语言A组;
import java.util.Scanner;
public class 路径之谜深搜 {
public static int a,t;
public static boolean flag[][];
public static int north[],west[];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
a = input.nextInt();
flag = new boolean[a][a];
north = new int[a];
for (int i = 0; i < a; i++) {
north[i] = input.nextInt();
t+=north[i];
}
west = new int[a];
for (int i = 0; i < a; i++) {
west[i] = input.nextInt();
}
north[0]--;
west[0]--;
flag[0][0] = true;
dfs(0, 0, 1,"0",north, west);
}
public static void dfs(int x ,int y, int step,String trace,int copynorth[],int copywest[]) {
if (x == a-1 && y == a-1 && step == t) {
if (check(copynorth) && check(copywest)) {
System.out.println(trace);
return;
}
}
int next [][] = {{0,1},{1,0},{0,-1},{-1,0}};
int tx,ty;
for (int i = 0; i < next.length; i++) {
tx = x+next[i][0];
ty = y+next[i][1];
if (tx >= a || ty >= a || tx < 0 || ty < 0) {
continue;
}
if (copynorth[ty]<0 || copywest [tx] < 0) {
break;
}
if (flag[tx][ty] == false) {
copynorth[ty]--;
copywest[tx]--;
flag[tx][ty] = true;
dfs(tx, ty, step+1, trace+" "+(tx*a+ty), copynorth, copywest);
copynorth[ty]++;
copywest[tx]++;
flag[tx][ty] = false;
}
}
}
public static boolean check(int num[]) {
for (int i = 0; i < num.length; i++) {
if (num[i] != 0) {
return false;
}
}
return true;
}
}