路径之谜
小明冒充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
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意:不要使用package语句。不要使用jdk1.7及以上版本的特性。
注意:主类的名字必须是:Main,否则按无效代码处理。
import java.util.Arrays;
import java.util.Scanner;
//路径之谜
public class _1_5 {
static int N;
static int[] north;// 正北方靶数
static int[] west;// 正西方靶数
static int[][] mark;// 用来标记是否经过某块石头,0为未经过,1为经过。
static int x, y;// 石头坐标,正东方向为x轴 南为y
// 移动坐标
static int[][] dis = { { 0, -1 }, { 0, 1 }, { 1, 0 }, { -1, 0 } };
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
// // 石头地面
// int map[][] = new int[N][N];
// 北边以及西边箭靶上的数字
north = new int[N];
west = new int[N];
mark = new int[N][N];
for (int i = 0; i < N; i++) {
north[i] = sc.nextInt();
}
for (int i = 0; i < N; i++) {
west[i] = sc.nextInt();
}
mark[0][0] = 1;
dfs("0");
}
public static void dfs(String s) {
if (x >= N - 1 && y >= N - 1) { // 走到终点
int[] north_count = new int[N];
int[] west_count = new int[N];
// 统计靶子上的数量
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
north_count[i] += mark[i][j];// 每列靶子上的箭数
west_count[i] += mark[j][i];// 每行靶子上的箭数
}
}
// 如果 目标与走过的靶数相等 输出s
if (Arrays.equals(north, north_count) && Arrays.equals(west, west_count)) {
System.out.println(s);
return;
}
}
// 向四个方向走
for (int i = 0; i < 4; i++) {
x += dis[i][0];
y += dis[i][1];
int position;
position = x + N * y;// 石头编号
String str = s + " " + position;
if (x >= 0 && y >= 0 && x < N && y < N && mark[x][y] == 0) {
mark[x][y] = 1;
dfs(str);
mark[x][y] = 0;// 回溯
}
x -= dis[i][0];
y -= dis[i][1];
}
}
}