示例#1
0
        /**
         * Applies an initial inference step and then calls the super class implementation.
         */

        public override Assignment <VAR, VAL> solve(CSP <VAR, VAL> csp)
        {
            if (inferenceStrategy != null)
            {
                csp = csp.copyDomains(); // do not change the original CSP!
                IInferenceLog <VAR, VAL> log = inferenceStrategy.apply(csp);
                if (!log.isEmpty())
                {
                    fireStateChanged(csp, null, null);
                    if (log.inconsistencyFound())
                    {
                        return(null);
                    }
                }
            }
            return(base.solve(csp));
        }
        /// <summary>
        /// Template method, which can be configured by overriding the three primitive operations below.
        /// </summary>
        /// <param name="csp"></param>
        /// <param name="assignment"></param>
        /// <returns>An assignment (possibly incomplete if task was cancelled) or null if no solution was found.</returns>
        private Assignment <VAR, VAL> backtrack(CSP <VAR, VAL> csp, Assignment <VAR, VAL> assignment)
        {
            Assignment <VAR, VAL> result = null;

            if (assignment.isComplete(csp.getVariables()) || currIsCancelled)
            {
                result = assignment;
            }
            else
            {
                VAR var = selectUnassignedVariable(csp, assignment);
                foreach (VAL value in orderDomainValues(csp, assignment, var))
                {
                    assignment.add(var, value);
                    fireStateChanged(csp, assignment, var);
                    if (assignment.isConsistent(csp.getConstraints(var)))
                    {
                        IInferenceLog <VAR, VAL> log = inference(csp, assignment, var);
                        if (!log.isEmpty())
                        {
                            fireStateChanged(csp, null, null);
                        }
                        if (!log.inconsistencyFound())
                        {
                            result = backtrack(csp, assignment);
                            if (result != null)
                            {
                                break;
                            }
                        }
                        log.undo(csp);
                    }
                    assignment.remove(var);
                }
            }
            return(result);
        }