The task.
Given a rectangular field D of the size (N, M) of cells (two-dimensional array). Each cell is written a number - the weight of the cell. From the cell (a, b) one can get into the cells (a + 1, b), (a, b + 1) or (a + 1, b + 1). You need to get from the cell (0, 0) into the cell (N - 1, M - 1). The route weight is calculated as the sum of the weights of the cells visited. Find the weight of the minimum route from (0, 0) to (N - 1, M - 1). In short, here is the formula:
G(0, 0) = D[0, 0] G(i, 0) = G(i - 1, 0) + D[i, 0], i > 0 G(0, j) = G(0, j - 1) + D[0, j], j > 0 G(i, j) = min(G(i - 1, j - 1), G(i - 1, j), G(i, j - 1)) + D[i, j], i > 0, j > 0 F(D) = G(N - 1, M - 1)
It’s impossible to write a properly working recursive function that calculates all this. Here is my option, but it is wrong. Where is the mistake? How to be right?
public static int sum =0; static int G(int i, int j, int[,] D) { if (i == 0 && j == 0) return D[0, 0]; if (j==0&&i!=0) { sum = G(i - 1, 0,D) + D[i, 0]; return G(i - 1, 0, D); } if (i==0&&j!=0) { sum = G(0, j - 1, D) + D[0, j]; return G(0, j - 1, D); } if (i!=0&j!=0) { sum = Math.Min(Math.Min(G(i - 1, j - 1, D), G(i - 1, j, D)), G(i, j - 1, D)) + D[i, j]; return G(i - 1, j - 1, D); } return 1; }
I rewrote the function without the sum, everything is exactly wrong.
static int G(int i, int j, int[,] D) { if (i == 0 && j == 0) { return D[0, 0]; } if (j==0&&i!=0) { return G(i - 1, 0, D) + D[i, 0]; } if (i==0&&j!=0) { return G(0, j - 1, D) + D[0, j]; } if (i!=0&j!=0) { return Math.Min(Math.Min(G(i - 1, j - 1, D), G(i - 1, j, D)), G(i, j - 1, D)) + D[i, j]; } return 1; }