Sudoku: Difference between revisions
Content added Content deleted
(Changed my →“Amb” Solution: to better and shorter →Recursive Backtrack Solution) |
(→Recursive Backtrack Solution: More fluent syntax) |
||
Line 1,835: | Line 1,835: | ||
namespace Sudoku { |
namespace Sudoku { |
||
static class Program { |
static class Program { |
||
private static bool Unique(IEnumerable<int> values) => values.Distinct().Count() == values.Count(); |
private static bool Unique(this IEnumerable<int> values) => values.Distinct().Count() == values.Count(); |
||
private static bool IsUnequal(IEnumerable<int> values) => |
private static bool IsUnequal(this IEnumerable<int> values) => values.Where(c => c != 0).Unique(); |
||
private static int RowCol(int rc) => rc <= 2 ? 0 : rc <= 5 ? 3 : 6; |
private static int RowCol(int rc) => rc <= 2 ? 0 : rc <= 5 ? 3 : 6; |
||
Line 1,844: | Line 1,844: | ||
select grid[r][c]; |
select grid[r][c]; |
||
private static bool Constraints(int[][] grid, int row, int col) => |
private static bool Constraints(this int[][] grid, int row, int col) => |
||
Range(0, 9).Select(c => grid[row][c]).IsUnequal() && |
|||
Range(0, 9).Select(r => grid[r][col]).IsUnequal() && |
|||
GetBox(grid, row, col).IsUnequal(); |
|||
private static (int, int) NextEmptyCell(int[][] grid, int r, int c) { |
private static (int, int) NextEmptyCell(this int[][] grid, int r, int c) { |
||
while (r < 9 && grid[r][c] != 0) { |
while (r < 9 && grid[r][c] != 0) { |
||
c = ++c % 9; |
c = ++c % 9; |
||
Line 1,857: | Line 1,857: | ||
} |
} |
||
private static (bool, int[][]) Solve(int[][] grid, int row, int col) { |
private static (bool, int[][]) Solve(this int[][] grid, int row, int col) { |
||
var (r, c) = NextEmptyCell( |
var (r, c) = grid.NextEmptyCell(row, col); |
||
if (r == 9) //success |
if (r == 9) //success |
||
Line 1,865: | Line 1,865: | ||
for (var i = 1; i <= 9; i++) { |
for (var i = 1; i <= 9; i++) { |
||
grid[r][c] = i; |
grid[r][c] = i; |
||
if (!Constraints( |
if (!grid.Constraints(r, c)) |
||
continue; |
continue; |
||
var (success, g) = Solve( |
var (success, g) = grid.Solve(r, c); |
||
if (!success) |
if (!success) |
||
continue; |
continue; |
||
Line 1,893: | Line 1,893: | ||
.ToArray(); |
.ToArray(); |
||
var (success, result) = Solve( |
var (success, result) = input.Solve(0, 0); |
||
if (success) |
if (success) |
||
Line 1,907: | Line 1,907: | ||
} |
} |
||
} |
} |
||
} |
|||
</lang> |
|||
Output |
Output |
||
<pre>975342861 |
<pre>975342861 |