At CodeFights I found a question about the validity of Sudoku grid. Given a grid, return true if it is valid, return false otherwise. The grid is valid when each row, each column and each 3x3 sub grid contains at most one occurrence of the numbers 1
to 9
.
I solved it using C# and I would like some feedback on my solution.
The provided grid is guaranteed to be 9x9 and to only contain the characters 1
through 9
and .
(for empty cells). So I did not include any error checking.
Solution
using System;
public static class Program
{
public static void Main()
{
char[][] grid = {
new char[] {'.', '.', '.', '1', '4', '.', '.', '2', '.'},
new char[] {'.', '.', '6', '.', '.', '.', '.', '.', '.'},
new char[] {'.', '.', '.', '.', '.', '.', '.', '.', '.'},
new char[] {'.', '.', '1', '.', '.', '.', '.', '.', '.'},
new char[] {'.', '6', '7', '.', '.', '.', '.', '.', '9'},
new char[] {'.', '.', '.', '.', '.', '.', '8', '1', '.'},
new char[] {'.', '3', '.', '.', '.', '.', '.', '.', '6'},
new char[] {'.', '.', '.', '.', '.', '7', '.', '.', '.'},
new char[] {'.', '.', '.', '5', '.', '.', '.', '7', '.'}
};
var sudoku = new Sudoku(grid);
Console.WriteLine(sudoku.IsValid());
}
}
public class Sudoku
{
char[][] _grid;
public Sudoku(char[][] grid)
{
_grid = grid;
}
public bool IsValid()
{
return RowsAreValid()
&& ColumnsAreValid()
&& SquaresAreValid();
}
bool RowsAreValid()
{
return Validate(GetNumberFromRow);
}
bool ColumnsAreValid()
{
return Validate(GetNumberFromColumn);
}
bool SquaresAreValid()
{
return Validate(GetNumberFromSquare);
}
bool Validate(Func<int, int, int> numberGetter)
{
for (var row = 0; row < 9; row++)
{
var usedNumbers = new bool[10];
for (var column = 0; column < 9; column++)
{
var number = numberGetter(row, column);
if (number != 0 && usedNumbers[number] == true)
{
return false;
}
usedNumbers[number] = true;
}
}
return true;
}
int GetNumberFromRow(int row, int column)
{
return ToNumber(_grid[row][column]);
}
int GetNumberFromColumn(int row, int column)
{
return ToNumber(_grid[column][row]);
}
int GetNumberFromSquare(int block, int index)
{
var column = 3 * (block % 3) + index % 3;
var row = index / 3 + 3 * (block / 3);
return ToNumber(_grid[row][column]);
}
int ToNumber(char c)
{
if (c == '.')
return 0;
return (int)(c - '0');
}
}
1
to9
. So, all empty cells is ok. \$\endgroup\$