function X = sudoku_solver(Y)
% Y is a 9x9 matrix representing the Sudoku puzzle to be solved.
% X is the solution to the Sudoku puzzle.
% Initialization
X = Y;
rows = [1, 2, 3, 4, 5, 6, 7, 8, 9];
cols = [1, 2, 3, 4, 5, 6, 7, 8, 9];
subs = [1, 2, 3, 10, 11, 12, 19, 20, 21];
% Check if the Sudoku puzzle is valid
if ~sudoku_check(Y)
error('Invalid Sudoku puzzle');
end
% Solve the Sudoku puzzle
[X, ~, ~] = sudoku_helper(X, rows, cols, subs);
end
function [X, row, col] = sudoku_helper(X, rows, cols, subs)
% Recursive helper function to solve the Sudoku puzzle.
% Find the first empty cell
idx = find(X == 0, 1);
if isempty(idx)
% If there are no empty cells, the Sudoku puzzle is solved.
row = 0;
col = 0;
return;
else
% Compute the row and column of the empty cell
[row, col] = ind2sub([9, 9], idx);
end
% Compute the possible values for the empty cell
used = [X(row, :), X(:, col)', X(subs((row-1) \ 3 + 1) + (cols((col-1) \ 3 + 1)-1) * 9)];
possible = setdiff(1:9, used);
% Try all possible values recursively
for i = 1:length(possible)
X(row, col) = possible(i);
[X, row, col] = sudoku_helper(X, rows, cols, subs);
if row == 0 && col == 0
% If the Sudoku puzzle is solved, return
return;
end
end
% If no solution is found, backtrack
X(row, col) = 0;
end
function valid = sudoku_check(X)
% Check if the Sudoku puzzle is valid.
% Check rows
valid = all(ismember(X, 1:9), 2);
% Check columns
valid = valid && all(ismember(X, 1:9), 1);
% Check subgrids
for i = 1:3
for j = 1:3
valid = valid && ismember([1:9], X(subs(i,:) + (subs(j,:) - 1) * 9));
end
end
end