过桥问题(dfs)

来源:互联网 发布:大数据相关论坛 编辑:程序博客网 时间:2024/05/01 02:33

这里写图片描述

用四个数表示四个物体,0,和1代表两岸,所以问题是(0,0,0,0)转换成(1,1,1,1),再用dfs就可以解决。

#include<iostream>using namespace std;int s[16];int xu(int a, int b, int c, int d){    return 1 * a + 2 * b + 4 * c + 8 * d;}int isOk(int a,int b,int c,int d){    if (b == c&&a != b) return 0;    if (c == d&&a != c) return 0;    return 1;}void show(){    int t = 15;    while (t)    {        cout << t<<" ";        t = s[t];    }    cout << endl;}void dfs(int a, int b, int c, int d){    if (a&&b&&c&&d){        show();        return;    }    if (!isOk(a,b,c,d)) return;    if (a == b&&!s[xu(1-a,1-b,c,d)]){        s[xu(1 - a, 1 - b, c, d)] = xu(a, b, c, d);        dfs(1 - a, 1 - b, c, d);        s[xu(1 - a, 1 - b, c, d)] = 0;    }    if (a == c&&!s[xu(1 - a,  b,1 - c, d)]){        s[xu(1 - a, b, 1 - c, d)] = xu(a, b, c, d);        dfs(1 - a, b, 1 - c, d);        s[xu(1 - a, b, 1 - c, d)]=0;    }    if (a == d&&!s[xu(1 - a, b,  c, 1-d)]){        s[xu(1 - a, b, c, 1 - d)] = xu(a, b, c, d);        dfs(1 - a, b, c, 1 - d);        s[xu(1 - a, b, c, 1 - d)] = 0;    }    if (!s[xu(1 - a, b, c, d)])    {        s[xu(1 - a, b, c,  d)] = xu(a, b, c, d);        dfs(1 - a, b, c, d);        s[xu(1 - a, b, c, d)] = 0;    }}int main(){    memset(s, 0, sizeof(s));    dfs(0, 0, 0, 0);    return 0;}
0 0
原创粉丝点击