コード例 #1
0
ファイル: Form1.cs プロジェクト: danvatamaniuc/SudokuSolver
        private void cmdSolve_Click(object sender, EventArgs e)
        {
            int currentNumber = -1;

            int[,] sudokuTable = new int[_size, _size];

            //extract the table from the datagridview
            for (int rows = 0; rows < dgvSudokuTable.Rows.Count; rows++)
            {
                for (int col = 0; col < dgvSudokuTable.Rows[rows].Cells.Count; col++)
                {
                    if (dgvSudokuTable.Rows[rows].Cells[col].Value == null)
                    {
                        sudokuTable[rows, col] = -1;
                    }
                    else
                    {
                        string value = dgvSudokuTable.Rows[rows].Cells[col].Value.ToString();

                        try
                        {
                            currentNumber = int.Parse(value);

                            if (currentNumber > _size)
                            {
                                throw new ValidationException("Sudoku table not valid! Allowed values are from 1 to " +
                                                              _size);
                            }
                        }
                        catch (ValidationException v)
                        {
                            MessageBox.Show(v.Message);
                            return;
                        }
                        catch (Exception)
                        {
                            MessageBox.Show(
                                "Something happened. Most likely you inserted a character instead of a number somewhere");
                            return;
                        }

                        sudokuTable[rows, col] = currentNumber;
                    }
                }
            }
            //end extraction of values from data grid view

            try
            {
                Validator.ValidateSudokuTable(sudokuTable);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                return;
            }

            int[,] solution;

            if (rbBFS.Checked)
            {
                solution = Solver.FindSolution(sudokuTable);
            }
            else
            {
                solution = Solver.FindSolutionGBFS(sudokuTable);
            }


            if (solution == null)
            {
                MessageBox.Show("A solution has not been found!");
                return;
            }

            for (int rows = 0; rows < dgvSudokuTable.Rows.Count; rows++)
            {
                for (int col = 0; col < dgvSudokuTable.Rows[rows].Cells.Count; col++)
                {
                    dgvSudokuTable.Rows[rows].Cells[col].Value = solution[rows, col];
                }
            }
        }