Recursive 2D Array Traversal
What value is printed when the program is executed?
public class PerimeterRecursive {
public static int perimeterSum(int[][] arr, int offset) {
int rows = arr.length;
int cols = arr[0].length;
if (offset >= rows - offset || offset >= cols - offset) return 0;
if (offset == rows - offset - 1 && offset == cols - offset - 1)
return arr[offset][offset];
int sum = 0;
// Top row of the current layer
for (int j = offset; j < cols - offset; j++)
sum += arr[offset][j];
// Bottom row of the current layer (if distinct)
if (offset != rows - offset - 1) {
for (int j = offset; j < cols - offset; j++)
sum += arr[rows - offset - 1][j];
}
// Left and right columns (excluding corners)
for (int i = offset + 1; i < rows - offset - 1; i++)
sum += arr[i][offset] + arr[i][cols - offset - 1];
return sum + perimeterSum(arr, offset + 1);
}
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
System.out.println(perimeterSum(grid, 0));
}
}
A
120
B
144
C
130
D
136
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE