Consider the following two algorithms to compute entries of . Assume that for both the algorithms, for all , has been initialized to .
Algorithm : For
For
Algorithm : For
For
For
If
Algorithm , is said to be correct if and only if it calculates the correct values of , for all , (as per the recursive formulation) at the end of the execution of the algorithm .
Which one of the following statements is true?
A
Step-by-Step Solution
Insight: DP table evaluation is correct if and only if every cell's dependencies are fully computed before the cell itself is evaluated.
Exam route: Check Algorithm B1 (row-major) and B2 (diagonal) against the dependency rule for T[i][j] = 2T[i-1][j] + 3T[i][j-1].
Learning route:
The recurrence requires T[i-1][j] (previous row) and T[i][j-1] (same row, previous column).
Algorithm B1 uses nested loops: outer i from 1 to n, inner j from 1 to n. When computing T[i][j], row i-1 is already complete, and in row i, column j-1 is already complete. This satisfies the dependency rule.
Algorithm B2 iterates by the sum of indices s = i + j from 2 to 2n. For any cell T[i][j] with sum s, its dependencies T[i-1][j] and T[i][j-1] both have an index sum of (i-1)+j = s-1 and i+(j-1) = s-1. Since the outer loop processes all cells with sum s-1 before any cell with sum s, all dependencies are guaranteed to be resolved.
Both algorithms are mathematically correct.