Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function [ puzzle, didSolve, backCount ] = solve_from_here( puzzle,row,col )
- %UNTITLED2 Summary of this function goes here
- % Detailed explanation goes here
- % Set the backtracking count to 0.
- backCount = 0;
- % If the row and column values indicate we've finished the puzzle,
- % set didSolve to true and return early from the function. We're done.
- if row==10 && col==1
- didSolve = true;
- return
- end
- % Compute the next row and next column positions, and store them in
- % variables. This way, whenever we need these values, we can just
- % use the variables. (Don't change row and col, use other variables.)
- nextRow= row;
- nextCol= col + 1;
- if nextCol==10
- nextCol= 1;
- nextRow= row+1;
- end
- % If this square in the puzzle already contains a default value, we shouldn't
- % change it. Instead, just recursively call solve_from_here, save its
- % returned values in our output variables, and return. (We don't need to
- % do any real work, but we do need to try to solve the rest of the puzzle
- % and send the results back to our caller.)
- if puzzle(row,col) ~= 0
- [puzzle, didSolve, bc] = solve_from_here(puzzle,nextRow,nextCol);
- backCount=backCount+bc;
- return
- end
- % Loop through guesses 1..9
- for i= 1:9
- % If the current guess can legally go in the puzzle at row, col
- if is_number_ok_here(puzzle,row,col,i)
- % Put the guess in the puzzle at row, col.
- puzzle(row,col) = i;
- % Recursively solve the puzzle from the next position. Save the
- % returned values in variables, and add the returned backtracking
- % count to our backtracking count.
- [puzzle, didSolve, bc] = solve_from_here(puzzle,nextRow,nextCol);
- backCount=backCount+bc;
- % If the recursive call solved the puzzle, set the output variables
- % correctly and return early from the function. We're done.
- if didSolve==true;
- return
- else
- % The guess was wrong. Remove it from the puzzle and increment
- % our backtracking count.
- puzzle(row,col)=0;
- backCount=backCount+1;
- end
- end
- end
- % After the loop ends, we've made all possible guesses, but no solution
- % was found. Set didSolve to false, and return the puzzle and
- % backtracking count as well.
- didSolve=false;
- return;
- end
Add Comment
Please, Sign In to add comment