1286: [蓝桥杯2016初赛]剪邮票 【中 / 全排列 / dfs / 连通块】

在这里插入图片描述
http://oj.ecustacm.cn/problem.php?id=1286

直接用dfs 是不可以的因为 dfs只可以走L型 不可以走T型
那么我们可以先用现有的全排列函数把所有的情况列出来,再判断其可不可以连通。

首先关键的一点在于将一位的数组映射到二维。
第二点就是如何判断是连通的
关于第二点就是用两个数组保存各个的方向。
如果可以走的话就把 1 恢复为 0 。
如果这个动作按照方向执行了5次说明就是连通的。


#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[12]={
    
    0,0,0,0,0,0,0,1,1,1,1,1};//一维 
int b[5][5];、、二维 
int xx[]={
    
    -1,1,0,0};//x方向 
int yy[]={
    
    0,0,1,-1};//y方向 
int ans;//总的方法 
int cnt;//统计走的次数 
void dfs(int x,int y)
{
    
    
	if(x<0||x>2||y<0||y>3) return; //越界退出 
	if(b[x][y]!=1) return;  //不可以走 
	cnt++;//走的步数加1
	 
	if(cnt==5)//走了5步,说明连通 
	{
    
    
		ans++;
		return;
	}
	
	b[x][y]=0;//走过后恢复为0  
	for(int i=0;i<4;i++)
	{
    
    
	    x=x+xx[i];
	    y=y+yy[i];
		dfs(x,y);
		
		x=x-xx[i];//恢复现场
	    y=y-yy[i];
	}
} 
int main(void)
{
    
    
	do
	{
    
    
		int x,y;
		for(int i=0;i<3;i++)
		{
    
    
			for(int j=0;j<4;j++)
			{
    
    
				if(a[i*4+j]==1)
				{
    
    
					x=i;
					y=j;
					b[i][j]=1;
				}
				else
				{
    
    
					b[i][j]=0;
				}
			}
		}
		dfs(x,y);
		cnt=0;
	}while(next_permutation(a,a+12));
	cout<<ans<<endl;
	return 0;
} 

另一种方法:

#include<bits/stdc++.h>
using namespace std;
int a[]={
    
    0,0,0,0,0,0,0,1,1,1,1,1};
int g[3][4];
void dfs(int x,int y)
{
    
    
    g[x][y]=0;
    if(x-1>=0&&g[x-1][y]==1)dfs(x-1,y);
    if(x+1<3&&g[x+1][y]==1)dfs(x+1,y);
    if(y-1>=0&&g[x][y-1]==1)dfs(x,y-1);
    if(y+1<4&&g[x][y+1]==1)dfs(x,y+1);


}
int check()
{
    
    
    int ans=0;
    for(int i=0;i<3;i++)
    {
    
    
        for(int j=0;j<4;j++)
        {
    
    
            if(g[i][j]==1)
            {
    
    
                 dfs(i,j);
                 ans++;//连通块数
            }

        }
    }
    return ans==1;//如果块数是1  说明是5个相连的
}
int main()
{
    
    
    int ans=0;
  do{
    
    

        for(int i=0;i<3;i++)
        {
    
    
            for(int j=0;j<4;j++)
            {
    
    
                if(a[i*4+j]==1)
                {
    
    
                    g[i][j]=1;
                }
                else{
    
    
                    g[i][j]=0;
                }
            }

        }

       if(check())
        ans++;
  }while(next_permutation(a,a+12));
  cout<<ans<<endl;
  return 0;
}

猜你喜欢

转载自blog.csdn.net/bettle_king/article/details/115413871