A valid Sudoku board has the following properties
- The board must be square (n-by-n). Let
m = sqrt(n)
- All rows must contain the numbers 1-n
- All columns must contain the numbers 1-n
- All nine m-by-m blocks must contain all numbers 1-n
The following MATLAB code verifies a Sudoku board of arbitrary sizes (where n
is a square number):
function correct_board = sudoku_checker(board)
correct_board = true;
[rows, cols] = size(board);
correct_size = (rows == cols) && mod(sqrt(rows),1) == 0;
if correct_size == false
disp('The board is not square')
correct_board = false
else
disp('The board is square')
for ii = 1:rows
if ~(isequal(unique(board(:,ii)), (1:rows)') && isequal(unique(board(ii,:)), (1:rows)))
disp(['Numbers ' num2str(1) '-' num2str(rows) ' are not present in all rows or columns'])
correct_board = false;
return
end
end
disp(['Numbers ' num2str(1), '-' num2str(rows) ' are present in all rows and columns'])
cell_blocks = mat2cell(board, repmat(sqrt(rows),sqrt(rows),1),repmat(sqrt(rows),sqrt(rows),1));
blocks_ok = all(arrayfun(@(x) isequal(unique(cell_blocks{x}),(1:rows)'), 1:rows));
if blocks_ok == true
disp(['All blocks are OK'])
else
disp(['All blocks are not OK'])
correct_board = false;
return;
end
disp('Board is OK')
end
end
A valid board will give the following output:
sudoku_checker(board)
The board is square
Numbers 1-9 are present in all rows and columns
All blocks are OK
Board is OK
An incorrect board will give an output like this (dependent on which condition that fails):
sudoku_checker(board)
The board is square
Numbers 1-4 are present in all rows and columns
All blocks are not OK
I'm wondering if there are ways to improve this code. I'm looking for improvements in performance and algorithm, as well as improvement in coding style etc.
Can I simplify any expressions? Remove some boolean operators?