题目:
剪邮票如【图1.jpg】, 有12张连在一起的12生肖的邮票。
现在你要从中剪下5张来,要求必须是连着的。
(仅仅连接一个角不算相连)
比如,【图2.jpg】,【图3.jpg】中,粉红色所示部分就是合格的剪取。
请你计算,一共有多少种不同的剪取方法。
答案:116
分析:
思路1:一开始我想着以每张邮票作为起点分别dfs,但是dfs无法同时走两边,解决不了T字型问题(舍弃)
思路2:从12张邮票中任选5张,用全排列枚举所有的组合,再用dfs判断是否连通
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int g[3][4];
int a[] = {0,0,0,0,0,0,0,1,1,1,1,1};
int k[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
int ans;
void dfs(int x,int y){
g[x][y] = 0;
//访问(x,y)的4个邻格
for(int i=0;i<4;i++){
int xx = x+k[i][0];
int yy = y+k[i][1];
if(xx>=0 && xx<3 && yy>=0 && yy<4){
if(g[xx][yy]==1){
dfs(xx,yy);
}
}
}
}
//检查连通性
bool check(){
//初始化并记录该状态所选择的格子
memset(g,0,sizeof(g));
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
if(a[i*4+j] == 1){//将一维数组映射到二维数组
g[i][j] = 1;
}
}
}
int cnt = 0;//记录连通块的数目
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
//如果g[i][j]选中,则将他周围所有也被选中的格子置0
if(g[i][j]==1){
dfs(i,j);
cnt++;
}
}
}
//如果cnt>1,说明存在不止一个区域
if(cnt==1) return true;
return false;
}
int main(){
do{
if(check()){
ans++;
}
}while(next_permutation(a,a+12));//next_permutation保证排列不重复
cout << ans;
return 0;
}