MuhammadTausif / leetcode_problems

MIT License
0 stars 0 forks source link

Solve 840 problem: Magic Cubes in a Grid #4

Closed MuhammadTausif closed 3 months ago

MuhammadTausif commented 3 months ago

840. Magic Squares In Grid

https://leetcode.com/problems/magic-squares-in-grid/

Medium Topics Companies A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.

Given a row x col grid of integers, how many 3 x 3 contiguous magic square subgrids are there?

Note: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up to 15.

Example 1:

Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Output: 1
Explanation: 
The following subgrid is a 3 x 3 magic square:

while this one is not:

In total, there is only one magic square inside the given grid.
Example 2:

Input: grid = [[8]]
Output: 0

Constraints:

MuhammadTausif commented 3 months ago

Problem Solved.

from typing import List

class Solution:
  def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
    def isMagic(i: int, j: int) -> int:
      s = "".join(str(grid[i + num // 3][j + num % 3])
                  for num in [0, 1, 2, 5, 8, 7, 6, 3])
      return s in "43816729" * 2 or s in "43816729"[::-1] * 2

    ans = 0

    for i in range(len(grid) - 2):
      for j in range(len(grid[0]) - 2):
        if grid[i][j] % 2 == 0 and grid[i + 1][j + 1] == 5:
          ans += isMagic(i, j)

    return ans