Sudoku: Difference between revisions
Content deleted Content added
→Functional Recursive Backtrack Solution: Greatly simplified Solve() |
|||
Line 1,855: | Line 1,855: | ||
: (r, c); |
: (r, c); |
||
private static |
private static bool Solve(this int[][] grid, int row, int col) { |
||
var (r, c) = grid.NextEmptyCell(row, col); |
var (r, c) = grid.NextEmptyCell(row, col); |
||
if (r == 9) //success |
if (r == 9) //success |
||
return |
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 |
if (grid.Constraints(r, c) && grid.Solve(r, c)) |
||
return true; |
|||
⚫ | |||
return (true, g); |
|||
} |
|||
} |
} |
||
grid[r][c] = 0; //backtrack |
grid[r][c] = 0; //backtrack |
||
return |
return false; |
||
} |
} |
||
Line 1,876: | Line 1,871: | ||
static void Main(string[] args) { |
static void Main(string[] args) { |
||
var |
var grid = new string[]{ |
||
"970 340 060", |
"970 340 060", |
||
"861 750 000", |
"861 750 000", |
||
Line 1,887: | Line 1,882: | ||
"040 007 300" } |
"040 007 300" } |
||
.Select(r => r.Where(c => c != ' ').Select(c => (int)c - '0').ToArray()) |
.Select(r => r.Where(c => c != ' ').Select(c => (int)c - '0').ToArray()) |
||
.ToArray() |
.ToArray(); |
||
.Solve(0, 0) switch { |
|||
var report = grid.Solve(0, 0) switch { |
|||
⚫ | |||
Range(0, 9) |
Range(0, 9) |
||
.Select(r => Range(0, 9).Select(c => |
.Select(r => Range(0, 9).Select(c => grid[r][c]).Fwd(string.Concat)) |
||
.Fwd(s => string.Join('\n', s)), |
.Fwd(s => string.Join('\n', s)), |
||
_ => |
|||
"No Solution\n" |
"No Solution\n" |
||
}; |
}; |