878164. Magic Square
Magic Square
Slug: magic-square Difficulty: Medium Id: 878164 Topic Tags: Arrays, Matrix Company Tags: None
Summary
The Magic Square problem involves creating a square matrix with distinct integers from 1 to n^2, such that each row, column, and diagonal sum up to the same value. This is an optimization problem that requires careful planning and execution.
Detailed Explanation
To solve this problem, we can start by initializing a 2D array of size n x n. Then, we fill in the array with numbers from 1 to n^2 such that each row, column, and diagonal sum up to the same value. We use a simple algorithm to achieve this.
Here's the step-by-step breakdown:
- Initialize an empty 2D array
arrof sizen x n. - Calculate the magic constant
m = (n * (n^2 + 1)) / 2. This is the sum that each row, column, and diagonal should have. - Fill in the array with numbers from 1 to
n^2. Start by filling the first row, then move diagonally towards the bottom-right corner, and finally fill in the remaining cells. - In each cell, calculate the sum of the current row, column, and diagonal. If this sum is equal to
m, set the value of the cell to 1; otherwise, increment the value by 1.
Here's an ASCII art diagram illustrating the filling process:
1 | 2 | 3
---------
4 | 5 | 6
---------
7 | 8 | 9
Time complexity: O(n^2) as we fill in the entire array. Space complexity: O(n^2) for storing the 2D array.
Optimized Solutions
Java
public class MagicSquare {
public static void main(String[] args) {
int n = 3; // Example size
int[][] arr = new int[n][n];
int m = (n * (n * n + 1)) / 2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = fill(arr, i, j, m);
}
}
}
public static int fill(int[][] arr, int i, int j, int m) {
if (i == j && i == (arr.length - 1) / 2) { // Bottom-right corner
return 1;
}
for (int k = 1; ; k++) {
if (k + i >= arr.length || k + j >= arr[0].length || arr[i][j] != 0) {
break;
}
arr[i][j] = k;
m -= k;
if (m == 0) {
return k;
}
}
return -1; // Error: Couldn't find a valid value
}
}