예제 #1
0
        public int[,] Solve()
        {
            //new_data - solve of sudoku
            var new_data = new int[9, 9];
            //check - true if all cells of sudoku are filled
            bool check = true;
            //check_1 - true, if there aren't cells that has filled
            bool check1 = true;

            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    //if in cell can stand only one number
                    if (Probably[i, j].Count == 1)
                    {
                        new_data[i, j] = Probably[i, j][0];
                        //if we fill at lest one cell - reset check_1
                        if (Field[i, j] == 0)
                        {
                            check1 = false;
                        }
                    }
                    else
                    {
                        //if in same cell aren't possible variants, sudoku hasn't solve
                        if (Probably[i, j].Count == 0)
                        {
                            throw new Exception("No solves!");
                        }
                        //if in the same cell can stand several numbers - reset check
                        new_data[i, j] = 0;
                        check          = false;
                    }
                }
            }
            //if all cells of sudoku are filled - this is solve, return his
            if (check)
            {
                return(new_data);
            }
            if (check1)
            {
                // if there aren't cells that has filled, find cell with a minimum number of possible options
                var num = Least_Options();
                foreach (var nums in Probably[num[0], num[1]])
                {
                    //try fill this cell in turn all possible options
                    try
                    {
                        new_data[num[0], num[1]] = nums;
                        //create new sudoku
                        var new_sud = new Sudoku(new_data);
                        //check his correctness
                        new_sud.Check();
                        //find solve
                        var res = new_sud.Solve();
                        //check his correctness
                        var sud_2 = new Sudoku(res);
                        sud_2.Check();
                        return(res);
                    }
                    //if in this case aren't solves - try next option
                    catch (Exception ea)
                    { }
                }
                throw new Exception("No solves!");
            }
            //if they are at least one cell that had filled - fill the cells again, into account the changes
            else
            {
                var sud = new Sudoku(new_data);
                return(sud.Solve());
            }
        }