Words arrange? :)
We go from the upper left corner and put the cost in the first row of each cell as the sum of cells to the left of it + itself (the first horizontal is reachable only to the left).
Further, in the second extreme left - this is the sum of the cost above it + it itself (only on top), and all others - the minimum value of the path above and on the left.
And so on to the end ... In a word, simple dynamic programming.
Now I will try to sketch on C ++.
Here, on the knee, since you are satisfied with any language ... The path is displayed in the reverse order - from the lower right to the upper left:
#include <iostream> #include <iomanip> using namespace std; int val[3][3] = { 1, 2, 3, 0, 4, 15, 0, 0, 7 }; int cost[3][3] = { 0 }; int pred[3][3] = {-1}; // 0 - ᢥаег, 1 - б«Ґў int main(int argc, const char * argv[]) { cost[0][0] = val[0][0]; for(int c = 1; c < 3; ++c) { cost[0][c] = cost[0][c-1] + val[0][c]; pred[0][c] = 1; } for(int r = 1; r < 3; ++r) { cost[r][0] = cost[r-1][0] + val[r][0]; pred[r][0] = 0; for(int c = 1; c < 3; ++c) { if (cost[r-1][c] < cost[r][c-1]) { cost[r][c] = val[r][c] + cost[r-1][c]; pred[r][c] = 0; } else { cost[r][c] = val[r][c] + cost[r][c-1]; pred[r][c] = 1; } } } cout << "Total cost: " << cost[2][2] << endl; int r = 2, c = 2; for(;;) { cout << "(" << r << "," << c << ") - "; if (pred[r][c]) --c; else --r; if (r == 0 && c == 0) { cout << "(0,0)\n"; break; } } }
Шагать можно только вниз или вправоwalkШагать можно только вниз или вправо- this is more interesting to remove) - vp_arth