public void Start() { initialBoard.Refactor(); currentBoard = SudokuBoard.DeepCopy(initialBoard); blankCells = currentBoard.GetPossibleGuesses(); if( !currentBoard.Solved()) GetPossibleGuesses(); Console.WriteLine("\n\tSolving...."); while (!currentBoard.Solved()) { int numBlankCells = currentBoard.GetNumberOfBlank(); TrySolving(); if (numBlankCells == currentBoard.GetNumberOfBlank()) RecursiveGuess(currentBoard, 0); if (currentBoard.Finished() && !currentBoard.Solved()) Restart(); } if (currentBoard.Finished() && currentBoard.Solved()) { sw.Stop(); Console.Clear(); Console.WriteLine("\n\tElapsed: {0}", sw.Elapsed); Console.WriteLine("\t{0} SOLUTION'S FOUND", solutions); currentBoard.PrintEverything(); } }
public void RecursiveGuess(SudokuBoard previous, int previousGuess) { bool blocked = false; bool fullyBlocked = false; int currentGuess = 0; SudokuBoard tempBoard = null; double seconds = sw.Elapsed.TotalSeconds; if (seconds % 5 < 0.001) { Console.WriteLine("\n\tElapsed: {0}", sw.Elapsed); Console.WriteLine("\t{0} solutions", solutions); } if (previous.CurrentlyVerified()) { if (!previous.Finished()) { tempBoard = SudokuBoard.DeepCopy(previous); blankCells = tempBoard.GetPossibleGuesses(); if (previousGuess != 0) { currentGuess = blankCells.First().possibilities.Find(x => x > previousGuess); if (currentGuess == 0) fullyBlocked = true; } else if (currentGuess < blankCells.First().possibilities.First()) { currentGuess = blankCells.First().possibilities.First(); } if (currentGuess != 0) blankCells.First().ForceCellValue(currentGuess); else blocked = true; if (tempBoard.Finished() && !tempBoard.Solved()) blocked = true; if (!blocked) RecursiveGuess(tempBoard, 0); } else if (previous.Solved()) { fullyBlocked = true; if (!previous.Equals(tempBoard)) currentBoard = SudokuBoard.DeepCopy(previous); solutions++; } } else fullyBlocked = true; if (!fullyBlocked) RecursiveGuess(previous, currentGuess); }
public Solve(SudokuBoard initial) { initialBoard = initial; solutions = 0; sw = new Stopwatch(); sw.Start(); }
private void btnPlay_Click(object sender, EventArgs e) { btnPlay.Enabled = false; btnPlay.Visible = false; btnNewBoard.Enabled = true; btnNewBoard.Visible = true; btnCheck.Enabled = true; btnCheck.Visible = true; btnSolve.Enabled = true; btnSolve.Visible = true; btnReset.Enabled = true; btnReset.Visible = true; lblInstructions.Visible = true; game = new SudokuBoard(9, difficulty); cardSize = 9; boardCell = new Button[cardSize, cardSize]; solvedBoard = new int[cardSize, cardSize]; game.printSudoku(); generateBoard(); game.getCells(ref boardCell); }
public void Start() { initialBoard.Refactor(); currentBoard = SudokuBoard.DeepCopy(initialBoard); blankCells = currentBoard.GetPossibleGuesses(); if (!currentBoard.Solved()) { GetPossibleGuesses(); } Console.WriteLine("\n\tSolving...."); while (!currentBoard.Solved()) { int numBlankCells = currentBoard.GetNumberOfBlank(); TrySolving(); if (numBlankCells == currentBoard.GetNumberOfBlank()) { RecursiveGuess(currentBoard, 0); } if (currentBoard.Finished() && !currentBoard.Solved()) { Restart(); } } if (currentBoard.Finished() && currentBoard.Solved()) { sw.Stop(); Console.Clear(); Console.WriteLine("\n\tElapsed: {0}", sw.Elapsed); Console.WriteLine("\t{0} SOLUTION'S FOUND", solutions); currentBoard.PrintEverything(); } }
static SudokuBoard ReadBoard(int[] rawBoard) { int n = rawBoard.Length; if(n != SudokuBoard.ROW * SudokuBoard.COLUM) throw new ArgumentException("raw board is not valid"); var rows = new List<int>(); var cols = new List<int>(); var vals = new List<int>(); for (int i = 0; i < n; i++) { if (rawBoard[i] != 0) { rows.Add(i / 9); cols.Add(i % 9); vals.Add(rawBoard[i]); } } var ret = new SudokuBoard(); ret.Init(rows.ToArray(), cols.ToArray(), vals.ToArray()); return ret; }
public SudokuBoard(SudokuBoard copy) { _maxValue = copy._maxValue; tiles = new SudokuTile[copy.Width, copy.Height]; CreateTiles(); // Copy the tile values foreach (var pos in SudokuBoard.Box(Width, Height)) { tiles[pos.Item1, pos.Item2] = new SudokuTile(pos.Item1, pos.Item2, _maxValue); tiles[pos.Item1, pos.Item2].Value = copy.tiles[pos.Item1, pos.Item2].Value; } // Copy the rules foreach (SudokuRule rule in copy.rules) { var ruleTiles = new HashSet <SudokuTile>(); foreach (SudokuTile tile in rule) { ruleTiles.Add(tiles[tile.X, tile.Y]); } rules.Add(new SudokuRule(ruleTiles, rule.Description)); } }
public void ParserText(string text, SudokuBoard sudokuBoard) { string[] lines = text.TrimEnd().Split(LineTermnation); if (lines.Length != sudokuBoard.SquareSize) { throw new ParseException("Text row count does not match board size"); } for (int i = 0; i < lines.Length; i++) { // List<string> characterColumns = new List<string>(); if (string.Join("", LineRegex.Split(lines[i])) != "") { throw new ParseException("Unknow characters"); } MatchCollection matches = LineRegex.Matches(lines[i]); if (matches.Count != sudokuBoard.SquareSize) { throw new ParseException("Text column count does not match board size"); //throw something here } foreach (Match match in matches) { sudokuBoard.AddSudokuSpace( new SudokuSpace() { SpaceCharter = match.Value, KnownValue = match.Value != UnknownTextValue, SpaceValue = match.Value != UnknownTextValue?int.Parse(match.Value):0 }, i, match.Index ); } } }
//Získá platné řešení aktuálního SudokuBoard public SudokuBoard GetSolution() { if (!IsValid()) { return(null); } if (IsSolved()) { return(this); } SolveBoard(this); if (solution == null) { return(null); } SudokuBoard board = new SudokuBoard(); board.data = board.solution = solution; return(board); }
public object Clone() { SudokuBoard clonedBoard = this.MemberwiseClone() as SudokuBoard; clonedBoard.Rows = new List <SudokuRow>(); foreach (SudokuRow row in Rows) { SudokuRow clonedRow = new SudokuRow(); clonedRow.SudokuRows.Clear(); foreach (SudokuElement element in row.SudokuRows) { SudokuElement clonedElemnt = new SudokuElement { Value = element.Value }; clonedElemnt.PossibleValues.Clear(); element.PossibleValues.ForEach(e => clonedElemnt.PossibleValues.Add(e)); clonedRow.SudokuRows.Add(clonedElemnt); } clonedBoard.Rows.Add(clonedRow); } return(clonedBoard); }
public void RecursiveGuess(SudokuBoard previous, int previousGuess) { bool blocked = false; bool fullyBlocked = false; int currentGuess = 0; SudokuBoard tempBoard = null; double seconds = sw.Elapsed.TotalSeconds; if (seconds % 5 < 0.001) { Console.WriteLine("\n\tElapsed: {0}", sw.Elapsed); Console.WriteLine("\t{0} solutions", solutions); } if (previous.CurrentlyVerified()) { if (!previous.Finished()) { tempBoard = SudokuBoard.DeepCopy(previous); blankCells = tempBoard.GetPossibleGuesses(); if (previousGuess != 0) { currentGuess = blankCells.First().possibilities.Find(x => x > previousGuess); if (currentGuess == 0) { fullyBlocked = true; } } else if (currentGuess < blankCells.First().possibilities.First()) { currentGuess = blankCells.First().possibilities.First(); } if (currentGuess != 0) { blankCells.First().ForceCellValue(currentGuess); } else { blocked = true; } if (tempBoard.Finished() && !tempBoard.Solved()) { blocked = true; } if (!blocked) { RecursiveGuess(tempBoard, 0); } } else if (previous.Solved()) { fullyBlocked = true; if (!previous.Equals(tempBoard)) { currentBoard = SudokuBoard.DeepCopy(previous); } solutions++; } } else { fullyBlocked = true; } if (!fullyBlocked) { RecursiveGuess(previous, currentGuess); } }
public static void PrintBoard(SudokuBoard board) { Console.WriteLine("Board:\n\n" + board.ToString()); }
public SudokuResolve(SudokuBoard board) { this.sudokuBoard = board; }
/// <summary> /// Creates a solver object for the specified Sudoku object. /// </summary> /// <param name="sudoku">The sudoku game object to use.</param> public SudokuSolver(SudokuBoard sudoku) { SudokuBoard = sudoku ?? new SudokuBoard(); InitializeBlackList(); }
public OneStepSudokuSolver(SudokuBoard startSudokuBoard, SudokuPossibleToSetItem sudokuPossibleToSetItem) { _sudokuPossibleToSetItem = sudokuPossibleToSetItem; }
private SolveResult SolveForManyWithIndicesToCheck(ISudokuSquare[] group, ref SolveResult result, List <int> indicesToCheck, GroupKind groupKind, List <List <int> > allNoteNumbers) { // We want to add the new logic! if (groupKind == GroupKind.Column || groupKind == GroupKind.Row) { // TODO: Group by block Dictionary <int, List <int> > blockMap = new Dictionary <int, List <int> >(); foreach (int index in indicesToCheck) { int key = group[index].Block; if (!blockMap.ContainsKey(key)) { blockMap.Add(key, new List <int>()); } List <int> allBlockNotes = blockMap[key]; List <int> notes = GetNumbers(group[index].Notes); foreach (int note in notes) { if (allBlockNotes.IndexOf(note) < 0) { allBlockNotes.Add(note); } } } if (blockMap.Count > 1) { foreach (int key in blockMap.Keys) { List <int> targetBlock = blockMap[key]; List <int> resultsForThisSubtraction = new List <int>(); resultsForThisSubtraction = targetBlock.ToList(); foreach (int sourceKey in blockMap.Keys) { List <int> sourceBlock = blockMap[sourceKey]; if (targetBlock == sourceBlock) { continue; } // We need to subtract!! foreach (int note in sourceBlock) { if (resultsForThisSubtraction.IndexOf(note) >= 0) { resultsForThisSubtraction.Remove(note); } } } // Subtraction for this block is done! if (resultsForThisSubtraction.Count > 0) { // Magic!!! We can remove these from other squares in the targetBlock! ISudokuSquare[] blocks = SudokuBoard.GetBlock(key); // We need to make sure that any blocks we examine are not among those already in group[indicesToCheck] } } } //foreach (List<int> noteNumbers in allNoteNumbers) //{ //} // TODO: Do we have more than one block? // Yes? It's magic!!! // TODO: Set Subtraction (e.g., b1 - b2) - b1 is the first block we subtract from // TODO: Set Subtraction the other (b2 - b1) - so b2 is the first block we subtract from // TODO: Anything left over??? // Yes? Then we can remove those leftover numbers from **all the other squares** in the first block we subtracted from. // LaterCommands.Add(new RemoveCommand(b2, "1, 3")); } List <int> allNumbersFound = new List <int>(); foreach (List <int> noteNumbers in allNoteNumbers) { AddNumbersTo(allNumbersFound, noteNumbers); } if (allNumbersFound.Count > indicesToCheck.Count) { return(SolveResult.None); } else { for (int i = 0; i < group.Length; i++) { if (indicesToCheck.Contains(i)) { continue; } // We can actually remove!!! if (RemoveNotesFrom(group[i], string.Join(", ", allNumbersFound)) == SolveResult.SquaresSolved) { result = SolveResult.SquaresSolved; } } } return(result); }
public static SudokuBoard ReturnSudokuBoard(string sudoku, out ArrayList originalData, out string errorMessage) { string[] u, v; bool noErrorFound; int i, j, n; errorMessage = null; originalData = new ArrayList(); SudokuBoard sudokuBoard = new SudokuBoard(); u = sudoku.Split(new string[] { "\r\n" }, StringSplitOptions.None); if (u.Length != 9) { errorMessage = "Not exactly 9 rows"; return(null); } i = 1; noErrorFound = true; while (noErrorFound && (i <= 9)) { v = u[i - 1].Split(' '); if (v.Length != 9) { errorMessage = "Row " + i.ToString() + " does not contain exactly 9 columns one blank separated"; noErrorFound = false; } else { j = 1; while (noErrorFound && (j <= 9)) { if (!int.TryParse(v[j - 1], out n)) { errorMessage = "The value \"" + v[j - 1] + "\" in row " + i.ToString() + " and column " + j.ToString() + " is not a valid integer"; noErrorFound = false; } else { if ((n < 0) || (n > 9)) { errorMessage = "The integer " + v[j - 1] + " in row " + i.ToString() + " and column " + j.ToString() + " is not in the range 0-9"; noErrorFound = false; } else if (n != 0) { try { sudokuBoard.SetItem(i - 1, j - 1, n); originalData.Add(new ThreeTupleOfIntegers(i - 1, j - 1, n)); } catch (Exception e) { errorMessage = e.Message; noErrorFound = false; } } } j++; } } i++; } if (!noErrorFound) { return(null); } return(sudokuBoard); }
void SelectSquare(int row, int column) { SudokuBoard.SelectSquare(row, column); }
static void Main(string[] args) { const string LOGO = @" _____ _ _ _____ _ / ___| | | | | / ___| | | \ `--. _ _ __| | ___ | | ___ _ \ `--. ___ | |_ _____ _ __ `--. \ | | |/ _` |/ _ \| |/ / | | | `--. \/ _ \| \ \ / / _ \ '__| /\__/ / |_| | (_| | (_) | <| |_| | /\__/ / (_) | |\ V / __/ | \____/ \__,_|\__,_|\___/|_|\_\\__,_| \____/ \___/|_| \_/ \___|_| by Daniel Herschel December 2020 "; Console.WriteLine(LOGO); string input; while (true) { string boardString = IOManager.GetBoard(); if (boardString.Equals("-1")) { Console.WriteLine("Did not get a board. Exiting..."); break; } SudokuBoard board = new SudokuBoard(boardString); if (board.Validate()) // Check if board is a valid Sudoku board { if (board.Size <= 16) // Check if the size is smaller that 16x16 { // Solving the board. IOManager.PrintBoard(board); Console.WriteLine("Press any key to solve the board."); _ = Console.ReadKey(); Console.WriteLine("\nSolving the board..."); // Create a stopwatch and start it. Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); if (board.Solve()) // Try to solve the Sudoku. { // Check time elapsed from the start of solving. stopwatch.Stop(); TimeSpan elapsed = stopwatch.Elapsed; // Print the board and time solved. IOManager.PrintBoard(board); Console.WriteLine("Board as one-line string: "); Console.WriteLine(board.ToOneLineString()); Console.WriteLine("Solved the board in " + elapsed.TotalMilliseconds + " ms."); // Export the board to text file if the user wants to. Console.WriteLine("\nDo you want to export the board into a text file? Y/N"); input = Console.ReadLine(); while (!input.ToLower().Equals("y") && !input.ToLower().Equals("n")) { Console.WriteLine("Invalid input. Please try again."); Console.WriteLine("Do you want to export the board into a text file? Y/N"); input = Console.ReadLine(); } if (input.ToLower().Equals("y")) { IOManager.ExportToFile(board.ToOneLineString()); } } else // If couldn't solve the Sudoku. { stopwatch.Stop(); // Stop the stopwatch. Console.WriteLine("Could not solve the Sudoku."); } } else // If the board is greater than 16x16. { Console.WriteLine("Board is too big (max 16x16)."); } } else // If the board is not a valid Sudoku board { Console.WriteLine("Invalid Sudoku board."); } Console.WriteLine("\nDo you want to enter another board? Y/N"); input = Console.ReadLine(); while (!input.ToLower().Equals("y") && !input.ToLower().Equals("n")) { Console.WriteLine("Invalid input. Please try again."); Console.WriteLine("Do you want to enter another board? Y/N"); input = Console.ReadLine(); } if (input.ToLower().Equals("n")) { break; } } // End while } // End main
public static SudokuBoard DeepCopy(SudokuBoard copy) { SudokuBoard other = (SudokuBoard) copy.MemberwiseClone(); other.board = new Cell[9,9]; other.rows = new List<Section>(); other.columns = new List<Section>(); other.regions = new List<Section>(); for (int i = 0; i < 9; i++) { other.rows.Add(new Section(SectionType.ROW)); // initialize each Row other.columns.Add(new Section(SectionType.COLUMN)); // initalize each Column other.regions.Add(new Section(SectionType.REGION)); // initialize each Region } // Initalize each cell with it's preset value and whether or not it's a blank (modifiable) square for (int i = 0; i < other.board.GetLength(0); i++) { for (int j = 0; j < other.board.GetLength(1); j++) { if ((copy.board[i, j].value > 0) && (copy.board[i, j].value <= 9)) // if coordinate is a preset cell, set it to value and isBlank false other.board[i, j] = new Cell(copy.board[i, j].value, false, j, i); else // else set it to zero and isBlank true other.board[i, j] = new Cell(0, true, j, i); } } // Assign each row and column it's group of cells List<Cell> rowCells = new List<Cell>(); List<Cell> colCells = new List<Cell>(); for (int i = 0; i < other.board.GetLength(0); i++) { for (int j = 0; j < other.board.GetLength(1); j++) { rowCells.Add(other.board[i, j]); // load up all cells in row colCells.Add(other.board[j, i]); // load up all cells in column } other.rows[i].AssignCells(rowCells); // set each rows cells other.columns[i].AssignCells(colCells); // set each columns cells rowCells = new List<Cell>(); // generate new List after each row as to not delete from memory colCells = new List<Cell>(); // generate new List after each column as to not delete from memory } // Assign each region it's group of cells List<Cell> regCells = new List<Cell>(); int reg = 0; for (int i = 0; i < other.board.GetLength(0); i += 3) { for (int j = 0; j < other.board.GetLength(1); j += 3) { for (int k = i; k < i + 3; k++) for (int l = j; l < j + 3; l++) regCells.Add(other.board[k, l]); // load up all cells in region other.regions[reg].AssignCells(regCells); // set each regions cells ++reg; // increment counter for List of regions regCells = new List<Cell>(); // generate new List after each region as to not delete from memory } } // Assign each cell their sections int regNum = 0; for (int i = 0; i < other.board.GetLength(0); i++) { for (int j = 0; j < other.board.GetLength(1); j++) { if ((j % 3 == 0) && (j != 0)) // step over one region horizontally every 3 cells regNum++; other.board[i, j].SetSections(other.rows[i], other.columns[j], other.regions[regNum]); } if (i < 2) // bring region back to 0 regNum = 0; else if (i < 5) // bring region back to 3 regNum = 3; else if (i < 8) // bring region back to 6 regNum = 6; } other.Refactor(); return other; }
//Načtení dat ze souboru do GameFormu public static void LoadIntoGameForm(GameForm gameForm, string fileName) { string saveFolder = Path.Combine(Program.SAVE_PATH, "games"); if (!Directory.Exists(saveFolder)) { Directory.CreateDirectory(saveFolder); } string saveFile = Path.Combine(saveFolder, fileName + ".sudoku"); if (!File.Exists(saveFile)) { return; } using (StreamReader reader = new StreamReader(new FileStream(saveFile, FileMode.Open))) { gameForm.name = reader.ReadLine().Trim(); int selectedIndex = int.Parse(reader.ReadLine().Trim()); gameForm.selectedField = new Point(selectedIndex % 9, selectedIndex / 9); SudokuBoard originalBoard = new SudokuBoard(); string sudokuText = reader.ReadLine().Trim(); int col = 0, row = 0; foreach (char letter in sudokuText) { int val = int.Parse(letter.ToString()); originalBoard.SetValue(col++, row, val); if (col == 9) { col = 0; row++; } } gameForm.originalBoard = originalBoard.Clone(); SudokuBoard board = new SudokuBoard(); string boardText = reader.ReadLine().Trim(); int bcol = 0, brow = 0; foreach (char bletter in boardText) { int bval = int.Parse(bletter.ToString()); board.SetValue(bcol++, brow, bval); if (bcol == 9) { bcol = 0; brow++; } } gameForm.board = board.Clone(); reader.Close(); } }
private static void CompleteSolve(int selectedPuzzle, SudokuBoard board) { Console.WriteLine("\nOriginal Board:"); board.Output(); SudokuFiles.WriteSolution(selectedPuzzle, board); }
static void Main(string[] args) { SudokuBoard board = new SudokuBoard("examples.txt", 0); board.Print(); }
static void Main(string[] args) { int[,] board = new int[9, 9]; board[0, 2] = 2; board[0, 4] = 3; board[0, 5] = 6; board[0, 8] = 5; //board[1, 1] = 5; board[1, 3] = 9; //board[1, 7] = 2; board[2, 1] = 6; board[2, 4] = 2; board[2, 7] = 4; board[3, 7] = 1; //board[3, 8] = 2; board[4, 0] = 1; board[4, 3] = 5; board[4, 5] = 7; board[4, 8] = 6; board[5, 0] = 3; //board[5, 1] = 7; //board[6, 1] = 3; board[6, 4] = 6; board[6, 7] = 8; board[7, 1] = 1; board[7, 5] = 2; //board[7, 7] = 6; board[8, 0] = 6; board[8, 3] = 4; board[8, 4] = 1; board[8, 6] = 2; /*board[0, 0] = 8; board[1, 2] = 3; board[1, 3] = 6; board[2, 1] = 7; board[2, 4] = 9; board[2, 6] = 2; board[3, 1] = 5; board[3, 5] = 7; board[4, 4] = 4; board[4, 5] = 5; board[4, 6] = 7; board[5, 3] = 1; board[5, 7] = 3; board[6, 2] = 1; board[6, 7] = 6; board[6, 8] = 8; board[7, 2] = 8; board[7, 3] = 5; board[7, 7] = 1; board[8, 1] = 9; board[8, 6] = 4;*/ SudokuBoard sudokuBoard = new SudokuBoard(board); sudokuBoard.Refactor(); sudokuBoard.PrintEverything(); Solve solve = new Solve(sudokuBoard); solve.Start(); }
private void InitializeSquares() { SudokuBoard.AddSquare(0, 0, tbx0_0); SudokuBoard.AddSquare(0, 1, tbx0_1); SudokuBoard.AddSquare(0, 2, tbx0_2); SudokuBoard.AddSquare(0, 3, tbx0_3); SudokuBoard.AddSquare(0, 4, tbx0_4); SudokuBoard.AddSquare(0, 5, tbx0_5); SudokuBoard.AddSquare(0, 6, tbx0_6); SudokuBoard.AddSquare(0, 7, tbx0_7); SudokuBoard.AddSquare(0, 8, tbx0_8); SudokuBoard.AddSquare(1, 0, tbx1_0); SudokuBoard.AddSquare(1, 1, tbx1_1); SudokuBoard.AddSquare(1, 2, tbx1_2); SudokuBoard.AddSquare(1, 3, tbx1_3); SudokuBoard.AddSquare(1, 4, tbx1_4); SudokuBoard.AddSquare(1, 5, tbx1_5); SudokuBoard.AddSquare(1, 6, tbx1_6); SudokuBoard.AddSquare(1, 7, tbx1_7); SudokuBoard.AddSquare(1, 8, tbx1_8); SudokuBoard.AddSquare(2, 0, tbx2_0); SudokuBoard.AddSquare(2, 1, tbx2_1); SudokuBoard.AddSquare(2, 2, tbx2_2); SudokuBoard.AddSquare(2, 3, tbx2_3); SudokuBoard.AddSquare(2, 4, tbx2_4); SudokuBoard.AddSquare(2, 5, tbx2_5); SudokuBoard.AddSquare(2, 6, tbx2_6); SudokuBoard.AddSquare(2, 7, tbx2_7); SudokuBoard.AddSquare(2, 8, tbx2_8); SudokuBoard.AddSquare(3, 0, tbx3_0); SudokuBoard.AddSquare(3, 1, tbx3_1); SudokuBoard.AddSquare(3, 2, tbx3_2); SudokuBoard.AddSquare(3, 3, tbx3_3); SudokuBoard.AddSquare(3, 4, tbx3_4); SudokuBoard.AddSquare(3, 5, tbx3_5); SudokuBoard.AddSquare(3, 6, tbx3_6); SudokuBoard.AddSquare(3, 7, tbx3_7); SudokuBoard.AddSquare(3, 8, tbx3_8); SudokuBoard.AddSquare(4, 0, tbx4_0); SudokuBoard.AddSquare(4, 1, tbx4_1); SudokuBoard.AddSquare(4, 2, tbx4_2); SudokuBoard.AddSquare(4, 3, tbx4_3); SudokuBoard.AddSquare(4, 4, tbx4_4); SudokuBoard.AddSquare(4, 5, tbx4_5); SudokuBoard.AddSquare(4, 6, tbx4_6); SudokuBoard.AddSquare(4, 7, tbx4_7); SudokuBoard.AddSquare(4, 8, tbx4_8); SudokuBoard.AddSquare(5, 0, tbx5_0); SudokuBoard.AddSquare(5, 1, tbx5_1); SudokuBoard.AddSquare(5, 2, tbx5_2); SudokuBoard.AddSquare(5, 3, tbx5_3); SudokuBoard.AddSquare(5, 4, tbx5_4); SudokuBoard.AddSquare(5, 5, tbx5_5); SudokuBoard.AddSquare(5, 6, tbx5_6); SudokuBoard.AddSquare(5, 7, tbx5_7); SudokuBoard.AddSquare(5, 8, tbx5_8); SudokuBoard.AddSquare(6, 0, tbx6_0); SudokuBoard.AddSquare(6, 1, tbx6_1); SudokuBoard.AddSquare(6, 2, tbx6_2); SudokuBoard.AddSquare(6, 3, tbx6_3); SudokuBoard.AddSquare(6, 4, tbx6_4); SudokuBoard.AddSquare(6, 5, tbx6_5); SudokuBoard.AddSquare(6, 6, tbx6_6); SudokuBoard.AddSquare(6, 7, tbx6_7); SudokuBoard.AddSquare(6, 8, tbx6_8); SudokuBoard.AddSquare(7, 0, tbx7_0); SudokuBoard.AddSquare(7, 1, tbx7_1); SudokuBoard.AddSquare(7, 2, tbx7_2); SudokuBoard.AddSquare(7, 3, tbx7_3); SudokuBoard.AddSquare(7, 4, tbx7_4); SudokuBoard.AddSquare(7, 5, tbx7_5); SudokuBoard.AddSquare(7, 6, tbx7_6); SudokuBoard.AddSquare(7, 7, tbx7_7); SudokuBoard.AddSquare(7, 8, tbx7_8); SudokuBoard.AddSquare(8, 0, tbx8_0); SudokuBoard.AddSquare(8, 1, tbx8_1); SudokuBoard.AddSquare(8, 2, tbx8_2); SudokuBoard.AddSquare(8, 3, tbx8_3); SudokuBoard.AddSquare(8, 4, tbx8_4); SudokuBoard.AddSquare(8, 5, tbx8_5); SudokuBoard.AddSquare(8, 6, tbx8_6); SudokuBoard.AddSquare(8, 7, tbx8_7); SudokuBoard.AddSquare(8, 8, tbx8_8); SudokuBoard.Initialize(); }
public SudokuSolver(SudokuBoard board) { this.board = board; }
public SudokuBoard(SudokuBoard curboard) { Array.Copy(curboard.Board, this.Board, this.Board.Length); }
protected SudokuBoard SolvePuzzleRecursion(ref SudokuBoard board) { bool foundKnow = false; bool deadSpace = false; SudokuSpace spaceWithPossbile = null; int rowOfLeast = -1; int colOfLeast = -1; if (board is null) { return(board); } if (!board.GetSpaces().All(i => i.KnownValue)) { for (int i = 0; i < board.SquareSize; i++) { IEnumerable <int> rowSpaces = SpacesValuesKnown(board.GetRowValues(i)); for (int j = 0; j < board.SquareSize; j++) { SudokuSpace space = board.GetSudokuSpace(i, j); if (!space.KnownValue) { IEnumerable <int> colSpaces = SpacesValuesKnown(board.GetColumnValues(j)); int uppperRow = i / 3; int upperColumn = j / 3; IEnumerable <int> block = SpacesValuesKnown(board.GetBlockValues(uppperRow * 3, upperColumn * 3, 3)); space.PosibleValues = (from pos in board.NumberRange.AsEnumerable() where !rowSpaces.Contains(pos) && !colSpaces.Contains(pos) && !block.Contains(pos) select pos).ToList(); if (space.PosibleValues.Count == 0) { deadSpace = true; } else if (space.PosibleValues.Count == 1) { foundKnow = true; space.KnownValue = true; space.SpaceValue = space.PosibleValues.First(); space.SpaceCharter = space.PosibleValues.First().ToString(); } else { if (spaceWithPossbile == null || spaceWithPossbile.PosibleValues.Count > space.PosibleValues.Count) { rowOfLeast = i; colOfLeast = j; spaceWithPossbile = space; } } } } } if (deadSpace) { board = null; } else if (foundKnow) { SolvePuzzleRecursion(ref board); } else if (rowOfLeast != -1) { SudokuSpace space = board.GetSudokuSpace(rowOfLeast, colOfLeast); foreach (int posibleValue in space.PosibleValues) { if (!(Solved is null)) { break; } SudokuBoard clone = board.Copy(); SudokuSpace cloneSpace = clone.GetSudokuSpace(rowOfLeast, colOfLeast); cloneSpace.PosibleValues = null; cloneSpace.KnownValue = true; cloneSpace.SpaceValue = posibleValue; cloneSpace.SpaceCharter = posibleValue.ToString(); SolvePuzzleRecursion(ref clone); if (Solved is null && !(clone is null) && clone.GetSpaces().All(i => i.KnownValue)) { Solved = clone; break; } } } } return(Solved is null? board:Solved); }
public static SudokuBoard DeepCopy(SudokuBoard copy) { SudokuBoard other = (SudokuBoard)copy.MemberwiseClone(); other.board = new Cell[9, 9]; other.rows = new List <Section>(); other.columns = new List <Section>(); other.regions = new List <Section>(); for (int i = 0; i < 9; i++) { other.rows.Add(new Section(SectionType.ROW)); // initialize each Row other.columns.Add(new Section(SectionType.COLUMN)); // initalize each Column other.regions.Add(new Section(SectionType.REGION)); // initialize each Region } // Initalize each cell with it's preset value and whether or not it's a blank (modifiable) square for (int i = 0; i < other.board.GetLength(0); i++) { for (int j = 0; j < other.board.GetLength(1); j++) { if ((copy.board[i, j].value > 0) && (copy.board[i, j].value <= 9)) // if coordinate is a preset cell, set it to value and isBlank false { other.board[i, j] = new Cell(copy.board[i, j].value, false, j, i); } else // else set it to zero and isBlank true { other.board[i, j] = new Cell(0, true, j, i); } } } // Assign each row and column it's group of cells List <Cell> rowCells = new List <Cell>(); List <Cell> colCells = new List <Cell>(); for (int i = 0; i < other.board.GetLength(0); i++) { for (int j = 0; j < other.board.GetLength(1); j++) { rowCells.Add(other.board[i, j]); // load up all cells in row colCells.Add(other.board[j, i]); // load up all cells in column } other.rows[i].AssignCells(rowCells); // set each rows cells other.columns[i].AssignCells(colCells); // set each columns cells rowCells = new List <Cell>(); // generate new List after each row as to not delete from memory colCells = new List <Cell>(); // generate new List after each column as to not delete from memory } // Assign each region it's group of cells List <Cell> regCells = new List <Cell>(); int reg = 0; for (int i = 0; i < other.board.GetLength(0); i += 3) { for (int j = 0; j < other.board.GetLength(1); j += 3) { for (int k = i; k < i + 3; k++) { for (int l = j; l < j + 3; l++) { regCells.Add(other.board[k, l]); // load up all cells in region } } other.regions[reg].AssignCells(regCells); // set each regions cells ++reg; // increment counter for List of regions regCells = new List <Cell>(); // generate new List after each region as to not delete from memory } } // Assign each cell their sections int regNum = 0; for (int i = 0; i < other.board.GetLength(0); i++) { for (int j = 0; j < other.board.GetLength(1); j++) { if ((j % 3 == 0) && (j != 0)) // step over one region horizontally every 3 cells { regNum++; } other.board[i, j].SetSections(other.rows[i], other.columns[j], other.regions[regNum]); } if (i < 2) // bring region back to 0 { regNum = 0; } else if (i < 5) // bring region back to 3 { regNum = 3; } else if (i < 8) // bring region back to 6 { regNum = 6; } } other.Refactor(); return(other); }
public ThreeTupleOfIntegers[] Process( SudokuBoard sudokuBoard, Random r, bool isDebug, out int numberOfItemsSetDueToAloneInCell, out int numberOfItemsSetDueToAlonePossibleInRowColumnAndOrSquare, out int totalNumberOfItemsPossibleToSetWithoutCausingConflict, out int numberOfErrorsNotPossibleToSetAnyItemInCell, out int numberOfErrorsNotUniqueItemAlonePossible, out bool simulated, out string debugString) { int i, j, k, n, numberOfItemsSetInIteration, squareIndex; string str = "", commaSeparatedStringOfIntegers, sudokuPossibleToSetItemStr; StringBuilder sb1, sb2, tmpStringBuilder; ArrayList itemsSet = new ArrayList(); ArrayList itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare = new ArrayList(); ThreeTupleOfIntegers[] ArrayOfThreeTupleOfIntegers; ThreeTupleOfIntegers threeTupleOfIntegers; int[] tmpIntArray = new int[9]; numberOfItemsSetInIteration = 0; numberOfItemsSetDueToAloneInCell = 0; numberOfItemsSetDueToAlonePossibleInRowColumnAndOrSquare = 0; numberOfErrorsNotPossibleToSetAnyItemInCell = 0; numberOfErrorsNotUniqueItemAlonePossible = 0; simulated = false; totalNumberOfItemsPossibleToSetWithoutCausingConflict = _sudokuPossibleToSetItem.totalNumberOfItemsPossibleToSetWithoutCausingConflict; sudokuPossibleToSetItemStr = _sudokuPossibleToSetItem.ToString(); if (totalNumberOfItemsPossibleToSetWithoutCausingConflict == 0) { debugString = "Not possible to set anything!!"; return(null); } sb1 = new StringBuilder(); sb2 = new StringBuilder("Result: The following ####REPLACE_NUMBER_OF_ITEMS##### item(s) are possible to set, {row, column, item}:\r\n\r\n"); tmpStringBuilder = new StringBuilder(); sb1.Append("\r\n------------------------Find cells to set------------------------\r\n\r\n"); for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { threeTupleOfIntegers = null; sb1.Append(string.Format("[{0}, {1}]: ", i + 1, j + 1)); squareIndex = (3 * (i / 3)) + (j / 3); if (sudokuBoard.ItemIsSet(i, j)) { sb1.Append(string.Format("Cell already set with item {0}.\r\n", sudokuBoard.ReturnItem(i, j).ToString())); } else { if (_sudokuPossibleToSetItem.numberOfPossibleItemsRows[i, j] == 0) { sb1.Append("ERROR!! Not possible to set any item in cell that does not cause conflict!\r\n"); numberOfErrorsNotPossibleToSetAnyItemInCell++; } else if (_sudokuPossibleToSetItem.numberOfPossibleItemsRows[i, j] == 1) { numberOfItemsSetDueToAloneInCell++; threeTupleOfIntegers = new ThreeTupleOfIntegers(i, j, _sudokuPossibleToSetItem.rows[i, j, 0]); itemsSet.Add(threeTupleOfIntegers); numberOfItemsSetInIteration++; sb1.Append(string.Format("CAN SET ITEM {0}. The item is alone in cell.\r\n", _sudokuPossibleToSetItem.rows[i, j, 0].ToString())); sb2.Append("{" + string.Format("{0}, {1}, {2}", i + 1, j + 1, _sudokuPossibleToSetItem.rows[i, j, 0]) + "}\r\n"); } else { tmpStringBuilder.Clear(); itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare.Clear(); for (k = 0; k < _sudokuPossibleToSetItem.numberOfPossibleItemsRows[i, j]; k++) { n = _sudokuPossibleToSetItem.rows[i, j, k]; if (IsItemAloneInRow(i, n)) { Utility.AddIfNotExistsAlready(itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare, _sudokuPossibleToSetItem.rows[i, j, k]); tmpStringBuilder.Append(string.Format("Item {0} alone possible in row. ", n.ToString())); } if (IsItemAloneInColumn(j, n)) { Utility.AddIfNotExistsAlready(itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare, _sudokuPossibleToSetItem.rows[i, j, k]); str = string.IsNullOrEmpty(tmpStringBuilder.ToString()) ? "" : ", "; tmpStringBuilder.Append(string.Format("Item {0} alone possible in column. ", n.ToString())); } if (IsItemAloneInSquare(squareIndex, n)) { Utility.AddIfNotExistsAlready(itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare, _sudokuPossibleToSetItem.rows[i, j, k]); tmpStringBuilder.Append(string.Format("Item {0} alone possible in squre. ", n.ToString())); } } if (itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare.Count == 0) { FillTempIntArray(_sudokuPossibleToSetItem.rows, i, j, _sudokuPossibleToSetItem.numberOfPossibleItemsRows[i, j], tmpIntArray); sb1.Append(string.Format("Unable to set item. Item(s) not causing conflict: {0}.\r\n", Utility.ReturnString(tmpIntArray, _sudokuPossibleToSetItem.numberOfPossibleItemsRows[i, j]))); } else { n = (int)itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare[0]; if (itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare.Count == 1) { numberOfItemsSetDueToAlonePossibleInRowColumnAndOrSquare++; } else { numberOfErrorsNotUniqueItemAlonePossible++; } threeTupleOfIntegers = new ThreeTupleOfIntegers(i, j, n); itemsSet.Add(threeTupleOfIntegers); numberOfItemsSetInIteration++; sb2.Append("{" + string.Format("{0}, {1}, {2}", i + 1, j + 1, n) + "}\r\n"); if (itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare.Count == 1) { sb1.Append(string.Format("CAN SET ITEM {0}. The item is alone possible (in row, column and/or cell). {1} \r\n", n.ToString(), tmpStringBuilder.ToString())); } else { commaSeparatedStringOfIntegers = Utility.ReturnCommaSeparatedStringOfIntegers(itemsPossibleToSetDueToAlonePossibleInRowColumnAndOrSquare); sb1.Append(string.Format("ERROR!! Not unique alone possible. The following items are possible to set with that rule: {0}. Anyway, set item {1}. {2}\r\n", commaSeparatedStringOfIntegers, n.ToString(), tmpStringBuilder.ToString())); } } } } if (threeTupleOfIntegers != null) { sudokuBoard.Set(threeTupleOfIntegers); _sudokuPossibleToSetItem.Update(sudokuBoard, threeTupleOfIntegers.rowIndex, threeTupleOfIntegers.columnIndex); } } sb1.Append("\r\n"); } if (numberOfItemsSetInIteration == 0) { simulated = true; ArrayOfThreeTupleOfIntegers = new ThreeTupleOfIntegers[1]; SudokuSimulateItem sudokuSimulateItem = new SudokuSimulateItem(); ArrayOfThreeTupleOfIntegers[0] = sudokuSimulateItem.ReturnItem(r, _sudokuPossibleToSetItem, out str); sudokuBoard.Set(ArrayOfThreeTupleOfIntegers[0]); _sudokuPossibleToSetItem.Update(sudokuBoard, ArrayOfThreeTupleOfIntegers[0].rowIndex, ArrayOfThreeTupleOfIntegers[0].columnIndex); } else { ArrayOfThreeTupleOfIntegers = new ThreeTupleOfIntegers[numberOfItemsSetInIteration]; for (i = 0; i < numberOfItemsSetInIteration; i++) { ArrayOfThreeTupleOfIntegers[i] = (ThreeTupleOfIntegers)itemsSet[i]; } if (isDebug) { SudokuSimulateItem sudokuSimulateItem = new SudokuSimulateItem(); ThreeTupleOfIntegers tmpThreeTupleOfIntegers = sudokuSimulateItem.ReturnItem(r, _sudokuPossibleToSetItem, out str); } } if (simulated) { debugString = sudokuPossibleToSetItemStr + sb1.ToString() + "\r\n\r\n----------------------------------- Simulate one item -----------------------------------\r\n\r\n" + str + "\r\n\r\n---------- Sudoku board after iteration ----------\r\n\r\n" + sudokuBoard.SudokuBoardString; } else { if (!isDebug) { debugString = sudokuPossibleToSetItemStr + sb1.ToString() + sb2.ToString().Replace("####REPLACE_NUMBER_OF_ITEMS#####", numberOfItemsSetInIteration.ToString()).TrimEnd() + "\r\n\r\n---------- Sudoku board after iteration ----------\r\n\r\n" + sudokuBoard.SudokuBoardString; } else { debugString = sudokuPossibleToSetItemStr + sb1.ToString() + sb2.ToString().Replace("####REPLACE_NUMBER_OF_ITEMS#####", numberOfItemsSetInIteration.ToString()).TrimEnd() + "\r\n\r\n---------- Sudoku board after iteration ----------\r\n\r\n" + sudokuBoard.SudokuBoardString + "\r\n\r\n----------------------------------- DEBUG Simulate one item -----------------------------------\r\n\r\n" + str; } } return(ArrayOfThreeTupleOfIntegers); }
internal IEnumerable <SudokuTile> TileBox(int startX, int startY, int sizeX, int sizeY) { return(from pos in SudokuBoard.Box(sizeX, sizeY) select tiles[startX + pos.Item1, startY + pos.Item2]); }
static void Main(string[] args) { int userInput = 0; SudokuBoard board = new SudokuBoard(" "); do { board.PrintBoard(); Console.WriteLine(); Console.WriteLine("Pick a menu option:"); Console.WriteLine("1. Verify the board."); Console.WriteLine("2. Place a value on the board."); Console.WriteLine("3. Find legal digits for a given row/column."); Console.WriteLine("4. Solve the board completely."); Console.WriteLine("5. Exit program."); if (!int.TryParse(Console.ReadLine(), out userInput) || userInput < 1 || userInput > 4) { Console.WriteLine(); Console.WriteLine("You have entered an incorrect input. Please try again."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); Console.Clear(); continue; } switch (userInput) { case 1: VerifyBoard(board); break; case 2: PlaceValue(board); break; case 3: FindLegalDigits(board); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); break; case 4: if (SolveBoardIterativelyWithQueue(ref board)) { Console.WriteLine("The board was solved successfully!"); board.PrintBoard(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } else { Console.WriteLine("The board was not solved correctly."); board.PrintBoard(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } userInput = 5; break; case 5: Console.WriteLine("Thanks for playing"); break; } Console.Clear(); } while (userInput != 5); }
public void Restart() { currentBoard = SudokuBoard.DeepCopy(initialBoard); blankCells = currentBoard.GetPossibleGuesses(); Start(); }
bool CheckForConflicts(int r, int c, bool setHasConflictedProperty = true) { ISudokuSquare thisSquare = SudokuBoard.squares[r, c]; string text = thisSquare.GetText(); if (string.IsNullOrWhiteSpace(text)) { return(false); } ISudokuSquare[] column = SudokuBoard.GetColumn(c); ISudokuSquare[] row = SudokuBoard.GetRow(r); ISudokuSquare[] block = SudokuBoard.GetBlock(r, c); bool isConflicted = false; for (int rowIndex = 0; rowIndex < 9; rowIndex++) { if (rowIndex != r && column[rowIndex].GetText() == text) { if (setHasConflictedProperty) { thisSquare.HasConflict = true; column[rowIndex].HasConflict = true; } isConflicted = true; } } for (int colIndex = 0; colIndex < 9; colIndex++) { if (colIndex != c && row[colIndex].GetText() == text) { if (setHasConflictedProperty) { thisSquare.HasConflict = true; row[colIndex].HasConflict = true; } isConflicted = true; } } for (int squareIndex = 0; squareIndex < 9; squareIndex++) { GetSquarePosition(block[squareIndex], out int blockRow, out int blockColumn); if (blockRow == r && blockColumn == c) { continue; } if (block[squareIndex].GetText() == text) { if (setHasConflictedProperty) { thisSquare.HasConflict = true; block[squareIndex].HasConflict = true; } isConflicted = true; } } return(isConflicted); }
static void Main(string[] args) { int[,] board = new int[9, 9]; board[0, 2] = 2; board[0, 4] = 3; board[0, 5] = 6; board[0, 8] = 5; //board[1, 1] = 5; board[1, 3] = 9; //board[1, 7] = 2; board[2, 1] = 6; board[2, 4] = 2; board[2, 7] = 4; board[3, 7] = 1; //board[3, 8] = 2; board[4, 0] = 1; board[4, 3] = 5; board[4, 5] = 7; board[4, 8] = 6; board[5, 0] = 3; //board[5, 1] = 7; //board[6, 1] = 3; board[6, 4] = 6; board[6, 7] = 8; board[7, 1] = 1; board[7, 5] = 2; //board[7, 7] = 6; board[8, 0] = 6; board[8, 3] = 4; board[8, 4] = 1; board[8, 6] = 2; /*board[0, 0] = 8; * board[1, 2] = 3; * board[1, 3] = 6; * board[2, 1] = 7; * board[2, 4] = 9; * board[2, 6] = 2; * board[3, 1] = 5; * board[3, 5] = 7; * board[4, 4] = 4; * board[4, 5] = 5; * board[4, 6] = 7; * board[5, 3] = 1; * board[5, 7] = 3; * board[6, 2] = 1; * board[6, 7] = 6; * board[6, 8] = 8; * board[7, 2] = 8; * board[7, 3] = 5; * board[7, 7] = 1; * board[8, 1] = 9; * board[8, 6] = 4;*/ SudokuBoard sudokuBoard = new SudokuBoard(board); sudokuBoard.Refactor(); sudokuBoard.PrintEverything(); Solve solve = new Solve(sudokuBoard); solve.Start(); }
// cooling constant = .7 public SudokuBoard recurseSolve(SudokuBoard board, double temperature, int iteration) { int initConflicts = numConflicts(board); var rng = new Random(); int square = (int)(rng.NextDouble() * 9); int xOffset = 0; int yOffset = 0; if (initConflicts == 0) { Console.WriteLine("Solution found!"); return(board); } switch (square) { case 0: xOffset = 0; yOffset = 0; break; case 1: xOffset = 0; yOffset = 3; break; case 2: xOffset = 0; yOffset = 6; break; case 3: xOffset = 3; yOffset = 0; break; case 4: xOffset = 3; yOffset = 3; break; case 5: xOffset = 3; yOffset = 6; break; case 6: xOffset = 6; yOffset = 0; break; case 7: xOffset = 6; yOffset = 3; break; case 8: xOffset = 6; yOffset = 6; break; } int x1, y1, x2, y2; do { x1 = (int)(rng.NextDouble() * 3); y1 = (int)(rng.NextDouble() * 3); x2 = (int)(rng.NextDouble() * 3); y2 = (int)(rng.NextDouble() * 3); } while (squaresUnchangable[(xOffset + x1) * 9 + (yOffset + y1)] || squaresUnchangable[(xOffset + x2) * 9 + (yOffset + y2)]); Console.WriteLine("x1: " + (xOffset + x1) + " y1: " + (yOffset + y1)); Console.WriteLine("x2: " + (xOffset + x2) + " y2: " + (yOffset + y2)); Console.WriteLine("iteration Number: " + iteration); iteration++; var boardCandidate = board.Clone(); boardCandidate[xOffset + x1, yOffset + y1] = board[xOffset + x2, yOffset + y2]; boardCandidate[xOffset + x2, yOffset + y2] = board[xOffset + x1, yOffset + y1]; int newConflicts = numConflicts(boardCandidate); if (newConflicts < initConflicts) { board = boardCandidate.Clone(); } else { double probability = Math.Exp((initConflicts - newConflicts) / temperature); double random = rng.NextDouble(); if (random <= probability) { board = boardCandidate.Clone(); } } /* * for(int i = 0; i < 9; i++) //print out the new board * { * for(int j = 0; j < 9; j++) * { * Console.Write(board[i][j] + " "); * } * Console.WriteLine(); * } * Console.WriteLine(); */ for (int row = 0; row < 9; row++) { Console.WriteLine(); if (row == 0) { Console.WriteLine("\n -----------------------"); } for (int col = 0; col < 9; col++) { if (board[row, col] != 0) { if (col == 0) { Console.Write("| "); } Console.Write(board[row, col] + " "); if (col == 2 | col == 5 | col == 8) { Console.Write("| "); } } else { if (col == 0) { Console.Write("| "); } Console.Write("-" + " "); if (col == 2 | col == 5 | col == 8) { Console.Write("| "); } } } if (row == 2 | row == 5 | row == 8) { Console.Write("\n -----------------------"); } } Console.WriteLine(); if (iteration > 4450) //added. 20000 before, 4450 { return(board); } double nextTemperature = updateTemp(temperature); return(recurseSolve(board, nextTemperature, iteration)); }