function [moves, vine] = solver(board, limit)
% SOLVER Sample solver for the MATLAB Vines Contest
% The MATLAB Contest Team
% Copyright 2011 The MathWorks, Inc.
moves = [];
bSize = size(board);
bestPath = [];
for ii = 1:bSize(1)
for jj = 1:bSize(2)
source = [ii jj];
path = source;
visited = zeros(bSize);
visited(source(1), source(2)) = 1;
path = findVine(board, source, visited, path);
if pathValue(board, path)>pathValue(board, bestPath)
bestPath = path;
end
end
end
vine = sub2ind(bSize,bestPath(:,1),bestPath(:,2));
function value = pathValue(board, path)
bSize = size(board);
value = 0;
for ii = 1:size(path,1)
bValue = board(path(ii,1), path(ii,2));
value = value + bValue;
end
function bestPath = findVine(board, source, visited, path)
bestPath = path;
bSize = size(board);
validMoves = 1:4; % 1 up, 2 down, 3 left, 4 right
if source(1) == 1
validMoves(validMoves==1) = [];
elseif source(1) == bSize(1)
validMoves(validMoves==2) = [];
end
if source(2) == 1
validMoves(validMoves==3) = [];
elseif source(2) == bSize(2)
validMoves(validMoves==4) = [];
end
% validMoves
if isempty(validMoves)
return
end
sourceValue = board(source(1), source(2));
newPath = path;
for ii = 1:length(validMoves)
target = source;
switch validMoves(ii)
case 1
target(1) = target(1) - 1;
case 2
target(1) = target(1) + 1;
case 3
target(2) = target(2) - 1;
case 4
target(2) = target(2) + 1;
end
targetValue = board(target(1), target(2));
if targetValue > sourceValue && visited(target(1), target(2))~=1 % change to >= to catch repeats
newSource = target;
newVisited = visited;
newVisited(target(1), target(2)) = 1;
newPath = [path; target];
newPath = findVine(board, newSource, newVisited, newPath);
if pathValue(board, newPath)>pathValue(board, bestPath)
bestPath = newPath;
end
end
end
|