前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剪邮票(bfs + dfs)别人的

剪邮票(bfs + dfs)别人的

作者头像
Yuyy
发布2022-06-28 18:57:23
1720
发布2022-06-28 18:57:23
举报
文章被收录于专栏:yuyy.info技术专栏

本文最后更新于 1163 天前,其中的信息可能已经有所发展或是发生改变。

代码语言:javascript
复制
#include<iostream> 
#include<algorithm>
#include<queue>
#include<cstring>

using namespace std;

int a[100];
int vis[4][5];    //下标为0的不用
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };

int result = 0;

struct node
{
    int x, y;
}s;

void bfs(int a[])
{
    memset(vis, 0, sizeof(vis));   //记得将vis置零,防止有残余的1
    int x, y;

    //把一维下标转换为二维坐标
    for (int i = 1; i <= 5; ++i)
    {
        if (a[i] % 4 == 0)
        {
            x = a[i] / 4;
            y = 4;
        }
        else
        {
            x = a[i] / 4 + 1;
            y = a[i] % 4;
        }
        vis[x][y] = 1;
    }

    s.x = x;
    s.y = y;

    queue<node>Q;
    Q.push(s);
    vis[s.x][s.y] = 0;
    int num = 1;

    node t;
    while (!Q.empty())
    {
        t = Q.front();
        Q.pop();
        
        for (int i = 0; i < 4; ++i)
        {
            int xx = t.x + dx[i];
            int yy = t.y + dy[i];
            if (xx >= 1 && xx <= 3 && yy >= 1 && yy <= 4 && vis[xx][yy] == 1)
            {
                ++num;    //每有一个相连,num就自增
                vis[xx][yy] = 0;
                s.x = xx;
                s.y = yy;
                Q.push(s);
            }
        }
    }

    if (num == 5)    //如果这5个数都相连    
    {
        ++result;
    }

}

void dfs(int step)  //从12个数中取出5个(即12取5的所有组合),存入一维数组a中(从下标1开始存储)
{
    if (step == 6)
    {
        bfs(a);        //用bfs判断取出的这5个数在图中是否相连
        return;
    }

    for (int i = 1; i <= 12; ++i)
    {
        if (i > a[step - 1])    //以递增的顺序选出,可以防止重复
        {
            a[step] = i;
            dfs(step + 1);
        }
    }

    
}

int main()
{
    memset(a, 0, sizeof(a));
    dfs(1);
    cout << result << endl;

    return 0;
}

Post Views: 193

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-4-21 2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档