Find all possible dominoes chains with recursion and backtracking [closed]

谁都会走 提交于 2019-11-30 07:42:50

问题


I'm working on a challange where I need to find all possibilities for linear chains of dominoes tiles. I understand the principle of recursion but not how to translate it to code. If someone could maybe explain the problem (solution) in simple steps, which I could then follow and try to code them.

Example:

Tiles : [3/4] [5/6] [1/4] [1/6]

Possible chain : [3/4]-[4/1]-[1/6]-[6/5]

It's allowed to flip the tiles. (switching the numbers)


回答1:


The process is very simple: you start with a collection of dominoes D, and an empty chain 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 code:

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 + "]";
    }
}

Algorithm:

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;
}

Your example:

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);
}    


来源:https://stackoverflow.com/questions/48206913/find-all-possible-dominoes-chains-with-recursion-and-backtracking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!