フィルターのクリア

what is wrong with this code?should i add instruction to declare X?

2 ビュー (過去 30 日間)
lotus
lotus 2013 年 3 月 29 日
function X = sudoku(X)
% SUDOKU Solve Sudoku using recursive backtracking.
% sudoku(X), expects a 9-by-9 array X.
% Fill in all “singletons”.
% C is a cell array of candidate vectors for each cell.
% s is the first cell, if any, with one candidate.
% e is the first cell, if any, with no candidates.
[C,s,e] = candidates(X);
while ~isempty(s) && isempty(e)
X(s) = C{s};
[C,s,e] = candidates(X);
end
% Return for impossible puzzles.
if ~isempty(e)
return
end
% Recursive backtracking.
if any(X(:) == 0)
Y = X;
z = find(X(:) == 0,1); % The first unfilled cell.
for r = [C{z}] % Iterate over candidates.
X = Y;
X(z) = r; % Insert a tentative value.
X = sudoku(X); % Recursive call.
if all(X(:) > 0) % Found a solution.
return
end
end
end
% ------------------------------
function [C,s,e] = candidates(X)
C = cell(9,9);
tri = @(k) 3*ceil(k/3-1) + (1:3);
for j = 1:9
for i = 1:9
if X(i,j)==0
z = 1:9;
z(nonzeros(X(i,:))) = 0;
z(nonzeros(X(:,j))) = 0;
z(nonzeros(X(tri(i),tri(j)))) = 0;
C{i,j} = nonzeros(z);
end
end
end
L = cellfun(@length,C); % Number of candidates.
s = find(X==0 & L==1,1);
e = find(X==0 & L==0,1);
end % candidates
end % sudoku
  3 件のコメント
lotus
lotus 2013 年 3 月 29 日
when i run this code it said that Input argument "X" is undefined.
Error in ==> sudoku at 10
[C,s,e] = candidates(X);
lotus
lotus 2013 年 3 月 29 日
how to fix this error?

サインインしてコメントする。

採用された回答

the cyclist
the cyclist 2013 年 3 月 29 日
It looks like you should be calling that function with the syntax
>> sudoku(X)
where X is a 9x9 array (which presumably represents the sudoku puzzle layout).
Is that what you are doing?
  4 件のコメント
Walter Roberson
Walter Roberson 2013 年 3 月 29 日
Assign a 9 x 9 matrix of initial values to a variable, such as Puzzle1. Then at the command line,
sodoku(Puzzle1)
lotus
lotus 2013 年 3 月 30 日
i got it..thank you for all the helps.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSudoku についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by