function colors = solver(A,targetRowAndColumn)
[nrow ncol]=size(A);
maxA = max(A(:)) * numel(A);
[targetRow, targetColumn] = ind2sub(size(A),targetRowAndColumn);
target = A(targetRow, targetColumn);
colors = [];
isflooded = false(nrow,ncol);
isflooded(1,1) = true;
if testelnum(A,-123456789,nrow,ncol,targetRow, targetColumn, isflooded)
numvec = sort(unique(A));
numvec(find(numvec == A(1,1)|numvec >= A(targetRow, targetColumn)|numvec == 0))=[];
A(1,1)
A(targetRow, targetColumn)
swcost = [];
for ii = 1:numel(numvec)
swcost(ii) = (A(targetRow, targetColumn) - numvec(ii))*sum(A(:)==numvec(ii));
% swcost(ii) = sum(A(:)==numvec(ii));
end
[a b] = sort(swcost)
numvec = numvec(b)
for ii = 1:numel(numvec)
if testelnum(A,numvec(ii),nrow,ncol,targetRow, targetColumn, isflooded)
%numvec(ii)
A(A==numvec(ii))=0;
end
end
[isflooded ne] = flooded2(isflooded,A,nrow, ncol);
A(isflooded) = A(1,1);
exitflag = false;
dist = repmat(((1:nrow)' - targetRow).^2,1,ncol) + repmat(((1:ncol) - targetColumn).^2,nrow,1);
dist(A==0)=nan;
% while ~isflooded(targetRow, targetColumn)
while ~isflooded(max(targetRow-1,1), targetColumn) & ~isflooded(targetRow, min(ncol,targetColumn+1)) & ~isflooded(min(nrow,targetRow+1), targetColumn) & ~isflooded(targetRow, max(1,targetColumn-1))
col = A(dist==min(min(dist(ne))) & ne);
colors = [colors col(1)];
A(1,1) = colors(end);
[isflooded ne] = flooded2(isflooded,A,nrow, ncol);
A(isflooded) = colors(end);
end
A(A <= A(targetRow, targetColumn))=0;
while sum(sum(ne(A~=0))) >= 3
avcols = unique(A(ne));
avcols(avcols==0)=[];
maxcount = 0;
for ii = 1:numel(avcols)
countne = sum(A(ne) == avcols(ii));
if (avcols(ii)-target)*countne < avcols(ii)
countne = 0
end
if countne > maxcount
maxcount = sum(A(ne) == avcols(ii));
col = avcols(ii);
end
end
if maxcount == 0; break; end
colors = [colors col(1)];
A(1,1) = colors(end);
[isflooded ne] = flooded2(isflooded,A,nrow, ncol);
A(isflooded) = colors(end);
end
colors = [colors target];
if maxA < (sum(A(:)) + sum(colors(:)))
colors = [];
end
end
end
function [isflooded ne] = flooded2(isflooded, A, nrow, ncol)
nflooded = 0;
while sum(isflooded(:)) ~= nflooded
nflooded = sum(isflooded(:));
nr = [false(nrow,1) isflooded(:,1:end-1)] & ~isflooded;
nl = [isflooded(:,2:end) false(nrow,1)] & ~isflooded;
nu = [isflooded(2:end,:);false(1,ncol)] & ~isflooded;
nd = [false(1,ncol);isflooded(1:end-1,:)] & ~isflooded;
ne = nr | nl | nu | nd;
isflooded = isflooded | ((A == A(1,1)) & ne);
end
end
function possible = testelnum(A, col, nrow, ncol,targetRow, targetColumn, isflooded)
A(A==col)=0;
A(A~=0)=1;
[isflooded ne] = flooded2(isflooded, A, nrow, ncol);
possible = isflooded(targetRow, targetColumn);
end
|