[蓝桥杯2016初赛]剪邮票

[蓝桥杯2016初赛]剪邮票

题目描述
如下图, 有12张连在一起的12生肖的邮票。现在你要从中剪下5张来,要求必须是连着的。(仅仅连接一个角不算相连)
在这里插入图片描述
比如,下面两张图中,粉红色所示部分就是合格的剪取。
在这里插入图片描述
在这里插入图片描述

请你计算,一共有多少种不同的剪取方法。
输出
请填写表示方案数目的整数。

package pro;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

public class Main {
	static int[] arr = {1,2,3,4,5,6,7,8,9,10,11,12};
	static int[][] num = {{0,1},{0,-1},{1,0},{-1,0}};
	static int[] vis = new int[12];
	static int[] res2 = new int[5];
	
	static Map<String,Integer> map = new HashMap<String,Integer>();
	static int cnt = 0,n;
	public static void main(String[] args) {
		dps(0,0);
		System.out.println(cnt);
	}
	
	static void dps(int i,int m) {
		if(i==5) {
			if(test()) {
				/*int[] array = new int[5];
				for(int j = 0; j < 5; j++)
					array[j] = res2[j];
				Arrays.sort(array);
				String s = "";
				for(int a:array)
					s += String.valueOf(a);
				if(map.containsKey(s)==false) {
					map.put(s, 1);
					cnt++;
				}*/
				cnt++;
					
			}
			
		}else {
			for(int k = 0; k < 12; k++) {
				if(vis[k]==0) {
					if(m>arr[k])          //剪枝
						continue;
					res2[i] = arr[k];
					vis[k] = 1;
					dps(i+1,arr[k]);
					vis[k] = 0;
				}
			}
		}
	}
	static boolean test() {
		int x=0,y=0;
		int[][] arr = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
		int[][] res = new int[3][4];
		int[][] vis2 = new int[3][4];
		for(int k = 0; k < 5; k++) {
			for(int i = 0; i < 3; i++) {
				for(int j = 0; j < 4; j++) {
					if(arr[i][j]==res2[k]) {
						if(k==0) {
							x = i;
							y = j;
						}
						res[i][j] = 1;
					}
				}
			}
		}
		
		int count = 1;
		 Queue<Point> queue = new LinkedList<Point>();
		 Point p1 = new Point(x,y);
		 vis2[x][y] = 1;
		 queue.add(p1);
		 while(!queue.isEmpty()) {
			 Point p = queue.poll();
			 for(int i = 0; i < 4; i++) {
				 int a = p.x + num[i][0];
				 int b = p.y + num[i][1];
				 if(a>=0&&a<3&&b>=0&&b<4&&vis2[a][b]==0&&res[a][b]!=0) {
					 count++;
					 queue.add(new Point(a,b));
					 vis2[a][b] = 1;
				 }
			 }
		 }
		 if(count==5) 
			 return true;
		 return false;
		 
	}
}
class Point{
	int x,y;

	public Point(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	
	
}

注:全排列+连通性判断
连通性判断方法:
1.并查集 并查集介绍
2.dfs
3.bfs

去重和连通性判断较麻烦

剪枝之后无需判重

2021-01-30

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值