蓝桥杯之剪邮票问题

如图1, 有12张连在一起的12生肖的邮票。
在这里插入图片描述

现在你要从中剪下5张来,要求必须是连着的。
(仅仅连接一个角不算相连)
比如,图2、图3中,粉红色所示部分就是合格的剪取。
在这里插入图片描述

在这里插入图片描述

请你计算,一共有多少种不同的剪取方法。
请填写表示方案数目的整数。
注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。

public class Main {

	static boolean[] book = new boolean[12];
	static int[] path = new int[5];
	static int[][] map = new int[3][4];
	static Set<String> set = new HashSet<String>();
	static int ans;

	public static void main(String[] args) {
		dfs(0);
		System.out.println(ans);
	}

	public static void dfs(int index) {
		if (index == 5) {
			int[] tmp = Arrays.copyOf(path, 5);
			Arrays.sort(tmp);
			String str = tmp[0] + "" + tmp[1] + "" + tmp[2] + "" + tmp[3] + "" + tmp[4];
			if (!set.contains(str) && check()) {
				set.add(str);
				ans++;
			}
		} else {
			for (int i = 0; i < 12; i++) {
				if (!book[i]) {
					book[i] = true;
					path[index] = i;
					dfs(index + 1);
					book[i] = false;
				}
			}
		}
	}

	public static boolean check() {
		map = new int[3][4];
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 4; j++) {
				for (int t = 0; t < 5; t++) {
					if (i * 4 + j == path[t]) {
						map[i][j] = 1;
					}
				}
			}
		}
		int cnt = 0;
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 4; j++) {
				if (map[i][j] == 1) {
					dfs_connect(i, j);
					cnt++;
				}
			}
		}
		return cnt == 1;
	}

	public static void dfs_connect(int i, int j) {
		map[i][j] = 0;
		if (i + 1 < 3 && map[i + 1][j] == 1)
			dfs_connect(i + 1, j);
		if (j + 1 < 4 && map[i][j + 1] == 1)
			dfs_connect(i, j + 1);
		if (i - 1 >= 0 && map[i - 1][j] == 1)
			dfs_connect(i - 1, j);
		if (j - 1 >= 0 && map[i][j - 1] == 1)
			dfs_connect(i, j - 1);
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值