📌  相关文章
📜  国际空间研究组织 | ISRO CS 2013 |问题 13(1)

📅  最后修改于: 2023-12-03 15:07:33.933000             🧑  作者: Mango

ISRO CS 2013 - Question 13

This is a coding question which tests the implementation skills of a programmer. The question requires the programmer to implement a function that checks if a given array is a magic square or not.

Problem Statement

A magic square is an arrangement of numbers (usually integers) in a square grid, where the numbers in each row, and in each column, and the numbers in the two diagonals, all have the same sum. For example, the following is a magic square of size 3x3:

  8  1  6
  3  5  7
  4  9  2

In this square, all rows sum up to 15, all columns sum up to 15, and both diagonals sum up to 15.

The task is to write a function is_magic_square(arr: List[List[int]]) -> bool which takes a 2D square array (arr) of size n x n as input, and returns True if it is a magic square, and False otherwise.

Constraints
  • The input array arr is guaranteed to be of size n x n, such that 1 <= n <= 15.
  • The input array arr is guaranteed to contain only distinct positive integers in the range [1, n^2].
Example
Input
arr = [
    [8, 1, 6],
    [3, 5, 7],
    [4, 9, 2]
]
Output
True
Solution

Following is a Python implementation of the is_magic_square function:

from typing import List

def is_magic_square(arr: List[List[int]]) -> bool:
    n = len(arr)
    magic_sum = n * (n * n + 1) // 2
    
    # check rows
    for i in range(n):
        if sum(arr[i]) != magic_sum:
            return False
    
    # check columns
    for j in range(n):
        col_sum = 0
        for i in range(n):
            col_sum += arr[i][j]
        if col_sum != magic_sum:
            return False
    
    # check diagonal 1
    dia1_sum = 0
    for i in range(n):
        dia1_sum += arr[i][i]
    if dia1_sum != magic_sum:
        return False
    
    # check diagonal 2
    dia2_sum = 0
    for i in range(n):
        dia2_sum += arr[i][n-i-1]
    if dia2_sum != magic_sum:
        return False
    
    return True

The function works by first calculating the magic sum, which is the sum that all rows, columns and diagonals should add up to. It then checks each row, column, and diagonal to see if their sum matches the magic sum.

The time complexity of this solution is O(n^2), and the space complexity is O(1).