I am trying to write a matlab code to check a solved 9X9 sudoku problem. I can't seem to get it to work. Any ideas where I went wrong?
2 次查看(过去 30 天)
显示 更早的评论
function valid = sudoku (m)
valid = (size(m) == [9, 9]);
if (~valid)
fprintf('Sudoku: size must be 9x9\n');
return;
end;
valid = ((min(min(m)) >= 0) && (max(max(m)) <= 9));
if (~valid)
fprintf(['Sudoku: ', ...
'all entries must be integers between 0 and 9\n']);
return;
end;
% 1. check rows
for row = 1:9,
count = zeros(1, 9);
for col = 1:9,
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: row %i looks bad\n', row);
return;
end;
end;
% 2. check columns
for col = 1:9,
count = zeros(1, 9);
for row = 1:9,
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: col %i looks bad\n', col);
return;
end;
end;
% 3. check subsquares
for k = 0:8,
count = zeros(1, 9);
rowBase = 3*floor(k/3);
colBase = 3*mod(k,3);
for col = colBase+(1:3),
for row = rowBase+(1:3),
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: subsquare %i looks bad\n', k+1);
return;
end;
end;
return;
1 个评论
dpb
2016-4-28
The following jumped out at me altho it's a nit and probably the rarest of cases--
"fprintf(['Sudoku: ', ... 'all entries must be integers between 0 and 9\n']);"
...
'all entries must be integers between 1 and 9, inclusive\n']);
回答(1 个)
MHN
2016-4-28
编辑:MHN
2016-4-28
It works fine !
m = randi(9,9,9);
valid = (size(m) == [9, 9]);
if (~valid)
fprintf('Sudoku: size must be 9x9\n');
return;
end;
valid = ((min(min(m)) >= 1) && (max(max(m)) <= 9));
if (~valid)
fprintf(['Sudoku: ', ...
'all entries must be integers between 1 and 9\n']);
return;
end;
% 1. check rows
for row = 1:9,
count = zeros(1, 9);
for col = 1:9,
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: row %i looks bad\n', row);
return;
end;
end;
% 2. check columns
for col = 1:9,
count = zeros(1, 9);
for row = 1:9,
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: col %i looks bad\n', col);
return;
end;
end;
% 3. check subsquares
for k = 0:8,
count = zeros(1, 9);
rowBase = 3*floor(k/3);
colBase = 3*mod(k,3);
for col = colBase+(1:3),
for row = rowBase+(1:3),
data = m(row, col);
if (data > 0)
count(data) = count(data)+1;
end;
end;
end;
valid = (max(count) <= 1);
if (~valid)
fprintf('Sudoku: subsquare %i looks bad\n', k+1);
return;
end;
end;
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!