// CSE 143, Summer 2012 // Uses recursive backtracking to solve the problem of whether // a group of dominoes can be lined up to produce a chain that starts and ends // with a particular number. import java.util.*; // for ArrayList public class SolveDominoes { public static void main(String[] args) { // [(1|4), (2|6), (4|5), (1|5), (3|5)] List dominoes = new ArrayList(); dominoes.add(new Domino(1, 4)); dominoes.add(new Domino(2, 6)); dominoes.add(new Domino(4, 5)); dominoes.add(new Domino(1, 5)); dominoes.add(new Domino(3, 5)); System.out.println(hasChain(dominoes, 5, 5)); // true System.out.println(hasChain(dominoes, 1, 5)); // true System.out.println(hasChain(dominoes, 1, 3)); // true System.out.println(hasChain(dominoes, 1, 6)); // false System.out.println(hasChain(dominoes, 1, 2)); // false } // Returns true if a chain of dominoes can be made from the given list // that starts and ends with the given numbers. Otherwise returns false. // Assumes that if start == end, it's trivial, so we should return true. // Precondition: 0 <= start,end <= 6 // Precondition: dominoes != null public static boolean hasChain(List dominoes, int start, int end) { if (start == end) { return true; // base case } else { for (int i = 0; i < dominoes.size(); i++) { //choose: pick a domino to start the chain Domino d = dominoes.remove(i); //explore if (d.first() == start) { if (hasChain(dominoes, d.second(), end)) { return true; } } else if (d.second() == start) { if (hasChain(dominoes, d.first(), end)) { return true; } } //un-choose dominoes.add(i, d); } return false; // tried all dominoes and none worked } } }