Exemplo n.º 1
0
        public static bool Backtrack(Game game)
        {
            if (game.IsComplete())
            {
                return(true);
            }

            for (var i = 0; i < 9; i++)
            {
                for (var j = 0; j < 9; j++)
                {
                    if (game.IsEmpty(i, j))
                    {
                        var possibilities = GetLinePossibilities(game, i)
                                            .Intersect(GetColumnPossibilities(game, j))
                                            .Intersect(GetSquarePossibilities(game, i, j));

                        foreach (var possibility in possibilities)
                        {
                            game.Set(i, j, possibility);
                            var result = Backtrack(game);

                            if (result == true)
                            {
                                return(true);
                            }
                        }

                        game.EmptyUp(i, j);

                        return(false);
                    }
                }
            }

            return(false);
        }