private void button_solve_Click(object sender, EventArgs e) { try { //numbers - array of input data var numbers = new int[9, 9]; //sorting through all textboxs for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (data[i, j].Text != "") { //read number and check the range var s = Convert.ToInt32(data[i, j].Text); if (s < 1 || s > 9) { throw new Exception("Invalid number!"); } numbers[i, j] = s; } //if in cell don't number - write 0 else { numbers[i, j] = 0; } } } //create new sudoku var sudoku = new Sudoku(numbers); //check the corectness of input data sudoku.Check(); //find solve of sudoku var solve = sudoku.Solve(); //print this solve for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { //if in cell don't number - write number in black if (data[i, j].Text == "") { data[i, j].ForeColor = Color.Black; data[i, j].Text = solve[i, j].ToString(); } else { if (Convert.ToInt32(data[i, j].Text) != solve[i, j]) { throw new Exception("Invalid Solve!"); } } } } } catch (Exception ea) { MessageBox.Show("Attention! Error!\n" + ea.Message); } }
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()); } }