Symmetric Matrix Check

easy Matrix (2D arrays)

Problem

A square matrix is symmetric when m[i][j] == m[j][i] for all i and j. Read a matrix and print true if it is symmetric. A matrix that is not square is never symmetric.

Constraints

  • 1 <= r, c <= 500

Examples

Input

2 2
1 2
2 1

Output

true

Solutions

Best approachTime O(n^2)Space O(1)

Only the half above the diagonal needs to be checked, because the other half is the mirror. That halves the work.

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  : true or false.
 * Approach: Compare mirrored elements.
 * Time    : O(n^2)
 * 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 boolean solve(int[][] m) {
        // Step 1: A matrix that is not square cannot be symmetric.
        if (m.length != m[0].length) {
            return false;
        }

        // Step 2: Compare each element above the diagonal with its mirror below the diagonal.
        for (int i = 0; i < m.length; i++) {
            for (int j = i + 1; j < m.length; j++) {
                if (m[i][j] != m[j][i]) {
                    return false;
                }
            }
        }
        return true;
    }

    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 need to be compared?