Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function [res,s] = boardSolve(board)
- % Code that solves sudoku boards recursively with a brute-force algorithm.
- %Checking if board is solved. Returns the board if it's been solved.
- if ~ismember(board,0)
- res = board;
- s = 0;
- return
- else
- % making a list of the coordinates of all empty points on the board
- [r,c] = find(board == 0);
- empties = [r,c];
- [x,y] = size(empties);
- possibles = zeros(x,9);
- % Makes a list of possible moves corresponding to each cell in the
- % variable 'empties'.
- for i = 1:x
- for j = 1:9
- possibles(i,j) = validity(board,empties(i,1),empties(i,2),j);
- end
- end
- % Checks if there are any possible moves at all. Returns if there
- % aren't.
- if ~ismember(possibles,1)
- res = board;
- s = 0;
- return
- end
- % Starts a for-loop that goes through every single legal placement
- % of numbers. One number is placed on the board and then this
- % function is called recursively with the new board.
- for i = 1:x
- for j = 1:9
- if possibles(i,j) == 1
- if ~ismember(board,0)
- res = board;
- s = 0;
- return
- else
- board(empties(i,1),empties(i,2)) = j;
- [res,s] = boardSolve(board);
- end
- end
- end
- end
- end
- end
- %Checks the validity of a placement
- function valid = validity(board,row,col,val)
- valid = 1;
- %Determines which region of the board a cell is in.
- q = squareFind(row,col);
- if val == 0
- valid = 1;
- elseif ismember(val,board(row,:)) || ismember(val,board(:,col))
- valid = 0;
- elseif ismember(val,board(q(1,:),q(2,:)))
- valid = false;
- end
- end
- %Determines which region of the board a cell is in.
- function mat = squareFind(row,col)
- if row<=3
- if col<=3
- x = 1;
- y = 1;
- elseif (col <=6)
- x = 1;
- y = 4;
- else
- x = 1;
- y = 7;
- end
- elseif row <=6
- if col<=3
- x = 4;
- y = 1;
- elseif (col <=6)
- x = 4;
- y = 4;
- else
- x = 4;
- y = 7;
- end
- else
- if col<=3
- x = 7;
- y = 1;
- elseif (col <=6)
- x = 7;
- y = 4;
- else
- x = 7;
- y = 7;
- end
- end
- [start] = [x,y];
- mat = [start(1):start(1)+2;start(2):start(2)+2];
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement