Clear Filters
Clear Filters

I need help fixing backtracking function on code for puzzle solver.

3 views (last 30 days)
Can't find what I'm missing in the code for this backtracking function to run correctly.
% Define the missing functions
function [imax, jmax, MaxScore] = findNextCell(P, HashRow, HashCol, HashBlock)
% Find the next cell with the least number of possible values
imax = 0; jmax = 0; MaxScore = -1;
for i = 1:16
for j = 1:16
if P(i,j) == -1
score = sum(HashRow(i,:)) + sum(HashCol(j,:)) + sum(sum(HashBlock(ceil(i/4),ceil(j/4),:)));
if score > MaxScore
MaxScore = score;
imax = i;
jmax = j;
else
end
end
end
end
end
  1 Comment
Dyuman Joshi
Dyuman Joshi on 30 Apr 2024
What is the objective here? What is the function suppossed to be doing?
What inputs are provided to it? And what are the corresponding expected outputs?

Sign in to comment.

Answers (2)

Sanju
Sanju on 6 May 2024
Hi Adrian,
The code you provided seems to be missing the main function that calls the findNextCell function. Without the main function, it is difficult to determine the exact issue you are facing. However, based on the provided code, I can see that the else statement inside the inner loop is empty. This might cause unexpected behavior in your code. You should either remove the else statement or add the necessary code inside it.
Here is an example of how you can call the findNextCell function from a main function,
function mainFunction()
% Define your input variables
P = ... % your input matrix
HashRow = ... % your input matrix
HashCol = ... % your input matrix
HashBlock = ... % your input matrix
% Call the findNextCell function
[imax, jmax, MaxScore] = findNextCell(P, HashRow, HashCol, HashBlock);
% Display the results
.......
end
Please provide more details or the complete code if you need further assistance.
Hope this helps!

John
John on 9 May 2024
it seems like you're trying to implement a function findNextCell that selects the next empty cell with the least number of possible values in a 16x16 grid for a puzzle solver using backtracking.
function [imax, jmax, MaxScore] = findNextCell(P, HashRow, HashCol, HashBlock)
% Find the next cell with the least number of possible values
imax = 0;
jmax = 0;
MaxScore = Inf; % Initialize MaxScore to a large value
for i = 1:16
for j = 1:16
if P(i,j) == -1
score = sum(HashRow(i,:)) + sum(HashCol(j,:)) + sum(HashBlock(ceil(i/4),ceil(j/4),:), 'all');
if score < MaxScore
MaxScore = score;
imax = i;
jmax = j;
end
end
end
end
end
effectiveness of this function depends on how the HashRow, HashCol, and HashBlock matrices are constructed and what they represent in your puzzle solver. Ensure that these matrices are properly initialized and updated to reflect the current state of the puzzle grid.

Categories

Find more on Special Functions in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!