Magic Square Checker
A magic square is an n x n matrix filled with distinct integers such that every row, column, and both diagonals all have the same sum. Given a 3x3 matrix consisting of numbers from 1 to 9, determine if it forms a magic square. Return 'true' if it is a magic square, otherwise return 'false'.
[ [ 8, 1, 6 ], [ 3, 5, 7 ], [ 4, 9, 2 ] ]
Explanation. This is one of the most famous magic squares. All rows, columns, and diagonals sum to 15.
[ [ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ] ]
Explanation. Another correct magic square. All rows, columns, and diagonals sum to 15.
[ [ 3, 5, 7 ], [ 8, 1, 6 ], [ 4, 9, 2 ] ]
Explanation. Although it uses the same numbers as a magic square, the sums of the rows, columns, and diagonals do not all match.
Follow-up: Can you extend your solution to check magic squares of larger sizes, such as 4x4 or 5x5?
The input matrix will be a 2D array of integers with dimensions 3x3, consisting of numbers from 1 to 9 without any repetitions.
- Views
- 4