Casa > C > Can We Solve Sudoku Using Matlab?

Can we solve Sudoku using MATLAB?

Yes we can.

Here is the code for the same.

Solving Sudoku Using Recursive Backtracking

  1. function X = sudoku(X)  
  2. % SUDOKU Solve Sudoku using recursive backtracking.  
  3. % sudoku(X), expects a 9-by-9 array X.  
  4. % Fill in all “singletons”.  
  5. % C is a cell array of candidate vectors for each cell.  
  6. % s is the first cell, if any, with one candidate.  
  7. % e is the first cell, if any, with no candidates.  
  8. [C,s,e] = candidates(X);  
  9. while ~isempty(s) && isempty(e)  
  10. X(s) = C{s};  
  11. [C,s,e] = candidates(X);  
  12. end  
  13. % Return for impossible puzzles.  
  14. if ~isempty(e)  
  15. return  
  16. end  
  17. % Recursive backtracking.  
  18. if any(X(:) == 0)  
  19. Y = X;  
  20. z = find(X(:) == 0,1); % The first unfilled cell.  
  21. for r = [C{z}] % Iterate over candidates.  
  22. X = Y;  
  23. X(z) = r; % Insert a tentative value.  
  24. X = sudoku(X); % Recursive call.  
  25. if all(X(:) > 0) % Found a solution.  
  26. return  
  27. end  
  28. end  
  29. end  
  30. % ------------------------------  
  31. function [C,s,e] = candidates(X)  
  32. C = cell(9,9);  
  33. tri = @(k) 3*ceil(k/3-1) + (1:3);  
  34. for j = 1:9  
  35. for i = 1:9  
  36. if X(i,j)==0  
  37. z = 1:9;  
  38. z(nonzeros(X(i,:))) = 0;  
  39. z(nonzeros(X(:,j))) = 0;  
  40. z(nonzeros(X(tri(i),tri(j)))) = 0;  
  41. C{i,j} = nonzeros(z)’;  
  42. end  
  43. end  
  44. end  
  45. L = cellfun(@length,C); % Number of candidates.  
  46. s = find(X==0 & L==1,1);  
  47. e = find(X==0 & L==0,1);  
  48. end % candidates  
  49. end % sudoku 

Source :- Solving Sudoku with MATLAB

De Siubhan

Como obter o código QR para o meu Instagram :: Há alguma fórmula para responder ao Sudoku? É possível que haja duas respostas em um quebra-cabeça Sudoku?