Leetcode 840: Magic Squares In Grid

grid47
grid47
Exploring patterns and algorithms
Aug 15, 2024 7 min read

Given a grid of integers, the task is to find how many 3x3 magic square subgrids are present in the given grid. A 3x3 magic square is a grid that contains distinct numbers from 1 to 9, such that each row, each column, and both diagonals have the same sum. The input grid can contain numbers ranging from 0 to 15, but only numbers between 1 and 9 are valid for forming a magic square.
Problem
Approach
Steps
Complexity
Input: You are given a 2D grid of integers. The grid may contain numbers from 0 to 15. You need to identify all 3x3 subgrids that form a magic square.
Example: Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Constraints:
• 1 <= row, col <= 10
• 0 <= grid[i][j] <= 15
Output: Return the count of 3x3 magic square subgrids in the given grid.
Example: Output: 1
Constraints:
• The output should be a non-negative integer representing the count of magic square subgrids.
Goal: The goal is to iterate through the grid and identify all possible 3x3 subgrids, check if they form a magic square, and count how many such squares exist.
Steps:
• Step 1: Iterate through all possible 3x3 subgrids in the given grid.
• Step 2: For each subgrid, check if it contains distinct numbers from 1 to 9.
• Step 3: Verify if the sum of each row, column, and both diagonals is the same.
• Step 4: If the subgrid forms a magic square, increment the count.
• Step 5: Return the count of magic square subgrids.
Goal: Ensure the input grid meets the specified dimensions and constraints.
Steps:
• Grid dimensions should be within the specified bounds: 1 <= row, col <= 10.
• Values in the grid should be between 0 and 15, but only values from 1 to 9 are considered for magic squares.
Assumptions:
• The grid contains integers within the specified range, but only numbers between 1 and 9 can form a valid magic square.
• The grid may contain numbers greater than 9, but they will not be considered part of the magic square.
Input: Input: [[4, 3, 8, 4], [9, 5, 1, 9], [2, 7, 6, 2]]
Explanation: In this grid, the subgrid containing the numbers 4, 3, 8, 9, 5, 1, 2, 7, 6 forms a valid 3x3 magic square because the sum of each row, column, and diagonal is 15.

Input: Input: [[8]]
Explanation: In this case, the grid is too small to contain any 3x3 subgrids, so the output is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus