第七届蓝桥杯决赛路径之谜

路径之谜

小明冒充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

借鉴别人的方法写了一下
import java.util.Arrays;
import java.util.Scanner;

/**
 * 路径之谜
 * @author yurong
 *
 */
public class MysteryPath {
	static int N;  
    static int []north;//正北方靶数  
    static int []west;//正西方靶数  
    static int[][]direction={{0,-1},{0,1},{-1,0},{1,0}};//上下左右移动方向  
    static int[][]mark;//用来标记是否经过某块石头,0为未经过,1为经过  
    static int x,y;//石头坐标,正东方向为x轴正方向,正南方向为y轴正方向  
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner console = new Scanner(System.in);
		//地面有N*N个方格
		N = console.nextInt();
		//北边以及西边箭靶上的数字
		north = new int[N];
		west = new int[N];
		mark = new int[N][N];
		for(int i = 0; i < N;i++){
			north[i] = console.nextInt();
		}
		for(int i = 0; i < N; i++){
			west[i] = console.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];//每行靶子上的箭数
				}
			}
			if(Arrays.equals(north, north_count)&&Arrays.equals(west, west_count)){
				System.out.println(s);
				return;
			}
		}
		
		//朝四个方向走
		for(int i = 0; i < 4; i++){
			x += direction[i][0];
			y += direction[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 -= direction[i][0];
			y-= direction[i][1];//回溯
		}
	}

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值