Code covered by the BSD License  

Highlights from
Fast Sudoku Solver

image thumbnail
from Fast Sudoku Solver by Yue Wu
An algorithm to mimic human solving procedure for Sudoku puzzles

sudoku_grid_candidates(I)
function candidates = sudoku_grid_candidates(I)
% Function: sudoku_grid_candidates
%           used for getting all possible reasonable numbers for each grid 
%           in 9x9 sudoku puzzle
%           
% Input: I = 9x9 sudoku puzzle (2D matrix)
%        for example: 
%          I = [0 0 0 3 0 1 7 0 0 ; 
%               1 0 0 0 4 0 0 2 0 ;
%               0 6 0 0 0 0 0 5 0 ;
%               9 0 0 4 0 5 0 0 0 ;
%               0 0 6 0 0 0 1 0 0 ;
%               0 0 0 2 0 6 0 8 9 ;
%               0 7 0 0 0 0 4 9 0 ;
%               0 8 0 0 5 0 0 0 2 ;
%               0 0 9 0 0 7 0 0 0 ;]
% Output: candiates = 9x9 cells for each cell listing possible numbers for
%         its corresponding grid
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This is a sub-function of the main function sudoku_yue and sub-function
% sudoku_stage1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% All copyrights reserved
% By Yue Wu
% 10/05/2009
% ECE Dept, Tufts Univ.
% MA, Medford 02155
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% 1. Initial settings
sizx = 9; 
candidates = {}; % initially assign an empty cell
plist = 1:9; % list of possible numbers for each grid
bocmap = [1 1 1 2 2 2 3 3 3]; % block map list, which means row 3 is on block row 1

%% 2. Calculate Candidats
    for i = 1:sizx
        for j = 1:sizx
            clear row col boc bocn alist alist
            if I(i,j) == 0 % if the grid is empty in the puzzle
                row = unique(I(i,:)); % existent numbers along its row
                col = unique(I(:,j)); % existent numbers along its column
                boc = I((bocmap(i)-1)*3+1:bocmap(i)*3,(bocmap(j)-1)*3+1:bocmap(j)*3); % crop its corresponding block
                bocn = unique(boc); % existent numbers in its block
                alist = union(union(row,col),bocn); % already existent numbers
                clist = setdiff(plist,alist); % numbers could be used in the grid
                candidates{i,j} = clist; % assign these numbers to the candidates cell
            else  % if the grid is already filled
                candidates{i,j} = I(i,j); % assign its number to candidats cell
            end
        end
    end

Contact us at files@mathworks.com