Sum of the Border Elements

easy Matrix (2D arrays)

Problem

Read a matrix. Print the sum of the elements in the first row, the last row, the first column and the last column. Count each element only once.

Constraints

  • 1 <= r, c <= 500

Examples

Input

3 3
1 2 3
4 5 6
7 8 9

Output

40

Solutions

Best approachTime O(r * c)Space O(1)

Adding the four sides one by one counts the four corners twice. Testing each element once with an or-condition avoids that mistake.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process a matrix.
 * Input   : r and c, then r rows of c integers.
 * Output  : The border sum.
 * Approach: One test for each element.
 * Time    : O(r * c)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[][] m) {
        long total = 0;
        int rows = m.length;
        int cols = m[0].length;

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                // Step 1: An element is on the border if it is in the first or last row, or in the first or last column.
                boolean onBorder = i == 0 || i == rows - 1 || j == 0 || j == cols - 1;

                // Step 2: One check for each element means no element is counted twice.
                if (onBorder) {
                    total += m[i][j];
                }
            }
        }
        return total;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int rows = scanner.nextInt();
        int cols = scanner.nextInt();
        int[][] m = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                m[i][j] = scanner.nextInt();
            }
        }
        System.out.println(solve(m));
    }
}
Hints (1)
  1. Which elements would be counted twice if you add four sides?