开发者

minimum L sum in a mxn matrix - 2

Here is my first question about maximum L sum and here is different and hard version of it.

Problem : Given a mxn positive integer matrix find the minimum L sum from 1th row to the 开发者_运维百科m'th row . L(4 item) likes chess horse move

Example : M = 3x3

0 1 2

1 3 2

4 2 1

Possible L moves are : (0 1 2 2), (0 1 3 2) (0 1 4 2) We should go from 1th row to the 3th row with minimum sum

I solved this with dynamic-programming and here is my algorithm :

1. Take a mxn another Minimum L Moves Sum array and copy the first row of main matrix. I call it (MLMS) 2. start from first cell and look the up L moves and calculate it

3. insert it in MLMS if it is less than exists value

4. Do step 2. until m'th row

5. Choose the minimum sum in the m'th row

Let me explain on my example step by step:

  1. M[ 0 ][ 0 ] sum(L1 = (0, 1, 2, 2)) = 5 ; sum(L2 = (0,1,3,2)) = 6; so MLMS[ 0 ][ 1 ] = 6

    sum(L3 = (0, 1, 3, 2)) = 6 ; sum(L4 = (0,1,4,2)) = 7; so MLMS[ 2 ][ 1 ] = 6

  2. M[ 0 ][ 1 ] sum(L5 = (1, 0, 1, 4)) = 6; sum(L6 = (1,3,2,4)) = 10; so MLMS[ 2 ][ 2 ] = 6

    ... the last MSLS is :

    0 1 2

    4 3 6

    6 6 6

    Which means 6 is the minimum L sum that can be reach from 0 to the m.

I think it is O(8*(m-1)n) = O(mn). Is there any optimal solution or dynamic-programming algorithms fit this problem?

Thanks, sorry for long question


How there can be both 0-th and m-th rows in a matrix with total m rows?

Anyway, a simple Dijkstra will give you an optimal path in O(n*m) (assuming you have a good data structure to find minimum in the list of not yet reached points).

Also, if your knight can move only down the board (it can be useful to move up sometimes to decrease total path weight), you can write simple DP. Just start from the bottom of the board and for each position calculate how much it'll take to reach bottom. Since you can do up to 4 moves from each position, it's a simple check for minimum. Something like this

for (int row = m - 1; row >= 0; --row) {
    for (int col = 0; col < m; ++col) {
        int path1 = a[row][col + 1] + a[row][col + 2] + a[row + 1][col + 2] + best[row + 1][col + 2];
        int path2 = a[row][col + 1] + a[row + 1][col + 1] + a[row + 2][col + 1] + best[row + 2][col + 1];
        int path3 = ...
        int path4 = ...
        best[row][col] = min(path1, path2, path3, path4);
    }
}

edit
Why do you need to go up? Imagine matrix like this (where * means some ridiculously big number, like 1000000000). Obviously, you'll have to go from (0, 0) to the right part of the board before you go down.

111111111111
111111111111
*********111
*********111

So, path will look like this

...1...1...1
11...1...1..
*********11.
*********11.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜