ProgrammingHardProduct company OA

What is printed?

What is printed?
int g[3][3] = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
int mp(int r, int c) {
    if (r == 0 && c == 0) return g[0][0];
    if (r < 0 || c < 0) return 1000;
    int a = mp(r - 1, c), b = mp(r, c - 1);
    return g[r][c] + (a < b ? a : b);
}
int main(void) { printf("%d", mp(2, 2)); }
  1. A. 6
  2. B. 12
  3. C. 8
  4. D. 7

Correct answer: D. 7

mp(r, c) is the cheapest sum along a path from the top-left that moves only right or down; 1000 acts as infinity for cells outside the grid. The best path is 1 → 3 → 1 → 1 → 1 = 7. Going straight down the left and along the bottom costs 1 + 1 + 4 + 2 + 1 = 9.

More C Programming questions

Exams that ask this topic