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
.
Refer to How to find the boundary elements of a matrix? to better understand the boundary elements of a matrix.
sum
initialized to zero.sum
variable.sum
variable.sum
.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));}}