Esempio n. 1
0
        private bool TrySolveGridWithAssumptions()
        {
            var     numberOfPossibleCells = 2;
            short   number = 1;
            SubGrid subGridWithNumberOfPossibleCells = null;

            while (numberOfPossibleCells <= 9)
            {
                while (number <= 9)
                {
                    subGridWithNumberOfPossibleCells = GetSubGridWithNumberOfPossibleCells(_mainGrid.SubGrids3x3, numberOfPossibleCells, number);
                    if (subGridWithNumberOfPossibleCells != null)
                    {
                        break;
                    }
                    subGridWithNumberOfPossibleCells = GetSubGridWithNumberOfPossibleCells(_mainGrid.Rows, numberOfPossibleCells, number);
                    if (subGridWithNumberOfPossibleCells != null)
                    {
                        break;
                    }
                    subGridWithNumberOfPossibleCells = GetSubGridWithNumberOfPossibleCells(_mainGrid.Columns, numberOfPossibleCells, number);
                    if (subGridWithNumberOfPossibleCells != null)
                    {
                        break;
                    }
                    number++;
                }
                if (subGridWithNumberOfPossibleCells != null)
                {
                    break;
                }
                numberOfPossibleCells++;
            }
            foreach (Cell cell in subGridWithNumberOfPossibleCells.Cells.Where((cell) => cell.CanHaveValue(number)))
            {
                cell.Value = number;
                var fullGrid = new FullGrid();
                fullGrid.CopyValues(_mainGrid);
                cell.Value = 0;
                var solver = new Solver(fullGrid);
                try
                {
                    if (solver.TrySolveGrid())
                    {
                        _mainGrid.CopyValues(fullGrid);
                        return(true);
                    }
                }
                catch
                {
                    //All but one of the assumptions should lead to invalid grid and raise an exception
                }
            }
            return(false);
        }
Esempio n. 2
0
 private void SolveGrid()
 {
     try
     {
         var solver = new Solver.Solver(_mainGrid);
         if (solver.TrySolveGrid())
         {
             RefreshAll();
         }
         else
         {
             MessageBox.Show("Can not solve this grid :(");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }