-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargestmagic_square.py
More file actions
47 lines (38 loc) · 1.48 KB
/
largestmagic_square.py
File metadata and controls
47 lines (38 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution:
def largestMagicSquare(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
max_size = min(rows, cols) # Maximum possible square size
for size in range(max_size, 1, -1):
for r in range(rows - size + 1):
for c in range(cols - size + 1):
if self.isMagic(grid, r, c, size):
return size # break immediately when found
return 1 # If no larger magic square found, smallest is 1
def isMagic(self, grid, r, c, size):
targetSum = 0
# Sum of first row
for j in range(size):
targetSum += grid[r][c + j]
# --- CHECK DIAGONALS FIRST ---
diag1 = diag2 = 0
for i in range(size):
diag1 += grid[r + i][c + i] # Main diagonal
diag2 += grid[r + i][c + size - 1 - i] # Anti-diagonal
if diag1 != targetSum or diag2 != targetSum:
return False
# --- THEN CHECK ROWS ---
for i in range(1, size): # Skip first row, already used for targetSum
s = 0
for j in range(size):
s += grid[r + i][c + j]
if s != targetSum:
return False
# --- THEN CHECK COLUMNS ---
for j in range(size):
s = 0
for i in range(size):
s += grid[r + i][c + j]
if s != targetSum:
return False
return True