Given a 2D $M \times N$ matrix with non-negative values, I would like to find a path going from top to bottom such that the sum of the path is minimum. My function is defined as follow:
findSeam[e_List] := Module[{f, t, p, i, j, k, nrows, ncols},
{nrows, ncols} = Dimensions[e];
f = Table[0, {i, nrows}, {j, ncols}];
t = Table[0, {i, nrows}, {j, ncols}];
For [j = 1, j <= ncols, j++,
f[[1, j]] = e[[1, j]];
t[[1, j]] = 0;
];
For [i = 2, i <= nrows, i++,
For [j = 1, j <= ncols, j++,
If [j == 1, k = j, k = j - 1];
If [f[[i-1, j]] < f[[i-1, k]], k = j];
If [j < ncols && f[[i-1, j+1]] < f[[i-1, k]], k = j + 1];
f[[i, j]] = e[[i, j]] + f[[i-1, k]];
t[[i, j]] = k - j;
];
];
p = Table[1, {i, nrows}];
For [j = 2, j <= ncols, j++,
i = p[[-1]];
If [f[[nrows, i]] > f[[nrows, j]],
p[[-1]] = j;
];
];
For [i = nrows - 1, i >= 1, i--,
j = p[[i+1]];
p[[i]] = j + t[[i+1, j]];
];
p
];
The computation complexity is only $O(MN)$. However, when I apply this function to a $900 \times 600$ matrix, it takes about 6 seconds to finish the computation.
Is my coding style wrong? Can my code be optimized such that it runs more quickly? Thank you.
e
or a function to generate the list so we can replicate your results and use them as a baseline? $\endgroup$ – Jagra Mar 22 '15 at 16:57e
ise = Norm[#]& /@ #& /@ ImageData@ImageConvolve[img, {{1,1,1},{1,-8,1},{1,1,1}}]
, whereimg
is a 900x600 image. $\endgroup$ – Purboo Mar 23 '15 at 1:48