Intermediate Level

Implement the matrixBlockSumCenter method that returns the block sum around the center using distance k.

The input contains an integer matrix matrix, its rows and cols, and an integer k.

Your task is to find the sum of the block around the center cell of the matrix. The center cell is calculated using integer division: rows / 2 and cols / 2.

The block includes all cells within k rows and k columns from the center, while staying inside matrix boundaries. For example, in a 3 × 3 matrix with k = 1, the block covers the whole matrix.

Example 1

Input
matrix (int[][]) = [[1,2,3],[4,5,6],[7,8,9]]
rows (int) = 3
cols (int) = 3
k (int) = 1
Returns (int) 45

Example 2

Input
matrix (int[][]) = [[1]]
rows (int) = 1
cols (int) = 1
k (int) = 1
Returns (int) 1

Example 3

Input
matrix (int[][]) = [[1,2],[3,4]]
rows (int) = 2
cols (int) = 2
k (int) = 1
Returns (int) 10

First calculate the center row and center column.

Then find the valid block boundaries. The start row cannot go below 0, and the end row cannot go beyond rows - 1. Apply the same boundary check for columns.

Finally, loop through all cells inside that block and add their values to the sum.

Pseudocode:

function matrixBlockSumCenter(matrix, rows, cols, k):
    centerRow = rows / 2
    centerCol = cols / 2
    startRow = max(0, centerRow - k)
    endRow = min(rows - 1, centerRow + k)
    startCol = max(0, centerCol - k)
    endCol = min(cols - 1, centerCol + k)
    sum = 0
    for i from startRow to endRow:
        for j from startCol to endCol:
            sum = sum + matrix[i][j]
    return sum
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.