Sudoku: Difference between revisions
Content added Content deleted
m (→“Manual” Solution: Better solution name) |
m (→Functional Recursive Backtrack Solution: Used standard sudoku string format) |
||
Line 1,834: | Line 1,834: | ||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
using System; |
using System; |
||
using System.IO; |
|||
namespace Sudoku { |
namespace Sudoku { |
||
Line 1,851: | Line 1,852: | ||
GetBox(grid, row, col).IsUnequal(); |
GetBox(grid, row, col).IsUnequal(); |
||
private static |
private static bool Solve(this int[][] grid, int r, int c) { |
||
if (r == 9) |
|||
⚫ | |||
⚫ | |||
private static bool Solve(this int[][] grid, int row, int col) { |
|||
var (r, c) = grid.NextEmptyCell(row, col); |
|||
⚫ | |||
return true; |
return true; |
||
⚫ | |||
⚫ | |||
foreach (var i in Range(1,9)) { |
foreach (var i in Range(1,9)) { |
||
grid[r][c] = i; |
grid[r][c] = i; |
||
if (grid.Constraints(r, c) && grid.Solve(r, c)) |
if (grid.Constraints(r, c) && grid.Solve(r, c)) |
||
return true; |
return true; |
||
grid[r][c] = 0; |
|||
} |
|||
return false; |
return false; |
||
} |
} |
||
static |
private static int[][] Parse(string input) => |
||
input |
|||
.Select((c, i) => (index: i, val: (int)c - '0')) |
|||
⚫ | |||
"861 750 000", |
|||
.ToArray(); |
|||
"219 584 673", |
|||
"487 236 519", |
|||
"653 971 284", |
|||
"738 425 196", |
|||
"002 010 048", |
|||
"040 007 300" } |
|||
⚫ | |||
.ToArray(); |
|||
static void Main(string[] args) { |
|||
//https://staffhome.ecm.uwa.edu.au/~00013890/sudoku17 format |
|||
var puzzle = "000028000800010000000000700000600403200004000100700000030400500000000010060000000"; |
|||
var grid = Parse(puzzle); |
|||
⚫ | |||
Write(grid.Solve(0, 0) |
Write(grid.Solve(0, 0) |
||
? string.Join('\n', grid.Select(row=>string.Concat(row))) |
? string.Join('\n', grid.Select(row=>string.Concat(row))) |
||
Line 1,892: | Line 1,888: | ||
</lang> |
</lang> |
||
Output |
Output |
||
<pre> |
<pre> |
||
617328945 |
|||
861759432 |
|||
894517236 |
|||
324168957 |
|||
325946781 |
|||
219584673 |
|||
978651423 |
|||
487236519 |
|||
256834179 |
|||
653971284 |
|||
143792658 |
|||
738425196 |
|||
731489562 |
|||
592613748 |
|||
489265317 |
|||
146897325 |
|||
</pre> |
562173894</pre> |
||
===“Automatic” Solution=== |
===“Automatic” Solution=== |