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

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

ISRO CS 2017 - Question 73

This is a question from the 2017 ISRO Computer Science examination. The problem statement is as follows:

A magic square of order n is an arrangement of the integers from 1 to n^2 in an n x n matrix, with each integer occurring exactly once, and such that the sum of the entries of any row, any column, or any diagonal is the same. Given an integer n, your task is to construct a magic square of order n.

Input Format:

The input contains a single integer n

Output Format:

The output contains n lines, each having n space separated integers representing the magic square.

Example Input:
3
Example Output:
8 1 6
3 5 7
4 9 2
Explanation:

The above matrix is a 3 x 3 magic square with a sum of 15 in each row, column, and diagonal.

Approach to Solve the Problem

One possible algorithm for generating a magic square of order n is as follows:

  1. Create an n x n matrix initialized with zeros.
  2. Set the row and column indices to the center of the first row and first column, respectively.
  3. For each number from 1 to n*n:
    1. Place the number in the current cell.
    2. Move to the next row and column.
    3. If a cell is already occupied or out of bounds, wrap around to the opposite side of the matrix.
  4. Return the magic square.

The algorithm can be implemented easily in Python. Here's the code:

def generate_magic_square(n):
    # Initialize the matrix with zeros
    magic_square = [[0 for _ in range(n)] for _ in range(n)]
    
    # Set the initial cell indices to the center of the first row and first column
    i, j = 0, n // 2
    
    for num in range(1, n*n+1):
        magic_square[i][j] = num
        
        # Move to the next cell
        i -= 1
        j += 1
        
        # If the cell is out of bounds, wrap around to the opposite side of the matrix
        if i < 0 and j < n:
            i = n-1
        elif j == n and i >= 0:
            j = 0
        elif i < 0 and j == n:
            i, j = n-2, 1
        elif magic_square[i][j] != 0:
            i, j = i+1, j-2
            
    # Print the magic square
    for row in magic_square:
        print(' '.join(map(str, row)))

The generate_magic_square function takes an integer n as input and prints the magic square of order n. Here's how you can use the function:

n = int(input())
generate_magic_square(n)
Conclusion

In this article, we have discussed one possible algorithm for generating a magic square of order n and provided an implementation in Python. The algorithm is simple and can be easily understood and modified to meet different requirements.