使用递归回溯解决Domino链

时间:2014-10-13 05:57:10

标签: c++ recursion

给出一个多米诺骨牌的矢量,我的程序应该能够匹配它们并按顺序放置它们如果不能解决则返回false。这就是我所拥有的,当它可以解决任何多米诺骨牌的顺序时它起作用,但如果它不可解决则它不会返回假:

bool SolveDominoChain(Vector<Domino> & chain, Vector<Domino> & remaining)
{
    int remainingSize = remaining.size();

    Vector<Domino>tempRemaining = remaining;
    Vector<Domino>tempChain = chain;

    if(remaining.isEmpty())
    {
        return true;
    }
    else
    {
        if(chain.isEmpty())
        {
            chain.add(remaining[0]);
            remaining.removeAt(0);
            chain[0].flip();        
            return SolveDominoChain(chain, 
        }
        for(int d = 0; d< remainingSize; d++)
        {
            if(chain[chain.size()-1].getBottom() == remaining[d].getTop())
            {
                chain.add(remaining[d]);
                remaining.removeAt(d);
                return SolveDominoChain(chain, remaining);
            }
            if(chain[chain.size()-1].getBottom() == remaining[d].getBottom())
            {
                remaining[d].flip();
                chain.add(remaining[d]);
                remaining.removeAt(d);
                return SolveDominoChain(chain, remaining);
            }

            remaining.add(chain[chain.size()-1]);
            chain.removeAt(chain.size()-1);

            return SolveDominoChain(chain, remaining);
        }           
        return false;
    }
    return false;
}

0 个答案:

没有答案