The essence of the problem: The NxM matrix is given; you need to find a path from the upper left to the lower right, moving either to the next cell down or to the right, each step costs so much. how much is written in the matrix.
Find the most "cheap" way is not a problem, enter the data, the initial value for the zero row and the zero column and calculate the result matrix, where d [n-1] [m-1] is the answer about the price of the path.
for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { d[i, j] = Math.Min(d[i - 1, j], d[i, j - 1]) + arr[i, j]; } } BUT! you need to save and (or at least) withdraw this path yourself
eg:
entrance:
3 4 5 9 4 3 3 1 6 9 8 6 8 12 output:
35 6 1 1 2 1 2 2 3 2 3 3 3 4 There was such an attempt
long x = 0, y = 0; StringBuilder path = new StringBuilder(""); appends(ref path, 0, 0); while (true) { if (x == m - 1 && y == n - 1) break; long a, b; if (y < n - 1) a = d[y + 1, x]; else a = Int64.MaxValue; if (x < m - 1) b = d[y, x + 1]; else b = Int64.MaxValue; if (a > b) { if (x < m - 1) x += 1; appends(ref path, y, x); } else { if (y < n - 1) y += 1; appends(ref path, y, x); } } Where appends() counts the number of calls (that is, the number of steps) and attributes to path (y+1) + " " + (x+1)
In simple examples, everything works, but there are such tests (which I do not know in advance) in which the code does not respond correctly, where and in what could be the error? or how best to complete this task?