Closed. This question needs to be more focused. It is not currently accepting answers. Learn more
想改进这个问题吗?更新问题,使其只关注一个问题editing this post
我正在做一个小酒馆,在那里我需要找到所有可能的多米诺骨牌线性链我了解递归的原理,但不知道如何将其转换为代码如果有人可以用简单的步骤来解释问题(解决方案),我可以按照这些步骤来编写代码。
例子:
瓷砖:[3/4][5/6][1/4][1/6]
可能链:[3/4]-[4/1]-[1/6]-[6/5]
允许翻转瓷砖(切换号码)

最佳答案

这个过程非常简单:从多米诺骨牌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);
}

10-08 19:05