How to find the sum of boundary elements of a matrix

Problem overview

Given a matrix, find the sum of boundary elements of the matrix.

For example, consider the below matrix:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

The sum of the boundary elements of the above matrix is as follows: boundary_sum = 1 + 2 + 3 + 6 + 9 + 8 + 7 + 4 = 40.

Algorithm

Refer to How to find the boundary elements of a matrix? to better understand the boundary elements of a matrix.

  1. Define a variable sum initialized to zero.
  2. Run two loops. One loop is iterating along the rows and the other is iterating along the columns. During the iteration, execute the following steps:
    1. If the row number is either zero or the last row (i.e, the total number of rows of the matrix = 1) then add the element at the current position to the sum variable.
    2. If the column number is either zero or the last column (i.e., the total number of columns of the matrix = 1) then add the element at the current position to the sum variable.
  3. Print the variable sum.
  • Time Complexity - O(N*N)
  • Space Complexity - O(1)

Implementation of the algorithm

import java.util.Arrays;
public class Main{
private static int printBoundarySum(int[][] matrix){
int numRows = matrix.length;
int numCols = matrix[0].length;
int sum = 0;
for(int i = 0; i < numRows; i++)
{
for(int j = 0; j < numCols; j++)
{
if (i == 0 || j == 0 || i == numRows - 1 || j == numCols - 1)
sum += matrix[i][j];
}
}
return sum;
}
private static void printMatrix(int[][] matrix){
for (int[] row : matrix)
System.out.println(Arrays.toString(row));
}
public static void main(String[] args){
int matrix[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8 , 9}};
printMatrix(matrix);
System.out.println("The boundary sum of the above matrix is " + printBoundarySum(matrix));
}
}
Sum of boundary elements of matrix
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources