栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

通过递归和回溯找到所有可能的多米诺骨牌链

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过递归和回溯找到所有可能的多米诺骨牌链

这个过程非常简单:首先从一组多米诺骨牌D和一条空链C开始。

for each domino in the collection:    see if it can be added to the chain (either the chain is empty, or the first     number is the same as the second number of the last domino in the chain.    if it can,         append the domino to the chain,        then print this new chain as it is a solution,        then call recursively with D - {domino} and C + {domino}    repeat with the flipped domino

Java代码:

public class Domino {    public final int a;    public final int b;    public Domino(int a, int b) {        this.a = a;        this.b = b;    }    public Domino flipped() {        return new Domino(b, a);    }    @Override    public String toString() {        return "[" + a + "/" + b + "]";    }}

算法:

private static void listChains(List<Domino> chain, List<Domino> list) {    for (int i = 0; i < list.size(); ++i) {        Domino dom = list.get(i);        if (canAppend(dom, chain)) { chain.add(dom); System.out.println(chain); Domino saved = list.remove(i); listChains(chain, list); list.add(i, saved); chain.remove(chain.size()-1);        }        dom = dom.flipped();        if (canAppend(dom, chain)) { chain.add(dom); System.out.println(chain); Domino saved = list.remove(i); listChains(chain, list); list.add(i, saved); chain.remove(chain.size()-1);        }    }}private static boolean canAppend(Domino dom, List<Domino> to) {    return to.isEmpty() || to.get(to.size()-1).b == dom.a;}

你的例子:

public static void main(String... args) {    List<Domino> list = new ArrayList<>();    // [3/4] [5/6] [1/4] [1/6]    list.add(new Domino(3, 4));    list.add(new Domino(5, 6));    list.add(new Domino(1, 4));    list.add(new Domino(1, 6));    List<Domino> chain = new ArrayList<>();    listChains(chain, list);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430762.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号