Skip to content

Commit

Permalink
Merge pull request #1 from tanhongit/main
Browse files Browse the repository at this point in the history
840. Magic Squares In Grid
  • Loading branch information
tanhongit authored Aug 13, 2024
2 parents ae5151e + b2ad759 commit c6cba75
Show file tree
Hide file tree
Showing 10 changed files with 206 additions and 6 deletions.
42 changes: 42 additions & 0 deletions .github/workflows/fork.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: 'Upstream Sync'

on:
push:
branches:
- '*'
schedule:
- cron: '0 0 * * *'

workflow_dispatch:

jobs:
sync_latest_from_upstream:
runs-on: ubuntu-latest
name: Sync latest commits from upstream repo

steps:
- name: Checkout target repo
uses: actions/checkout@v4
with:
ref: main

- name: Sync upstream changes
id: sync
uses: aormsby/[email protected]
with:
target_sync_branch: main
target_repo_token: ${{ secrets.GITHUB_TOKEN }}
upstream_sync_branch: main
upstream_sync_repo: Algorithms-and-Chickens/leetcode
upstream_repo_access_token: ${{ secrets.UPSTREAM_REPO_SECRET }}

- name: New commits found
if: steps.sync.outputs.has_new_commits == 'true'
run: echo "New commits were found to sync."

- name: No new commits
if: steps.sync.outputs.has_new_commits == 'false'
run: echo "There were no new commits."

- name: Show value of 'has_new_commits'
run: echo ${{ steps.sync.outputs.has_new_commits }}
Binary file added medium/840. Magic Squares In Grid/assets/img.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 39 additions & 0 deletions medium/840. Magic Squares In Grid/description.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
URL: [840. Magic Squares In Grid
](https://leetcode.com/problems/magic-squares-in-grid/description/)

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.

![img.png](assets/img.png)

**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:

![img_1.png](assets/img_1.png)

while this one is not:

![img_2.png](assets/img_2.png)
-
In total, there is only one magic square inside the given grid.

**Example 2:**

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

**Constraints:**

- `row == grid.length`
- `col == grid[i].length`
- `1 <= row, col <= 10`
- `0 <= grid[i][j] <= 15`
113 changes: 113 additions & 0 deletions medium/840. Magic Squares In Grid/solution-php.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Solution URL

https://leetcode.com/discuss/topic/5611092/solution-100-beats-in-php-with-explanation/

# Intuition

To determine how many `3x3` subgrids within a given grid are magic squares, we need to check each possible `3x3` subgrid.

**A magic square** is defined as a grid where the sums of rows, columns, and diagonals are all equal and contain the numbers from 1 to 9 exactly once.

# Approach

1. **Grid Size Check**:

First, we check if the grid has fewer than 3 rows or columns.

If it does, return 0 because no `3x3` subgrid can exist.

2. **Iterate Over Subgrids**:
Use nested loops to iterate over all possible `3x3` subgrids in the grid.

3. **Helper Function**:
For each subgrid, use a helper function to:
- Ensure all numbers from 1 to 9 are present exactly once.
- Check if the sums of all rows, columns, and diagonals are equal.

4. **Count Valid Subgrids**:
Increment a counter for each valid magic square subgrid found.
If the helper function returns true, increment the counter `$res`.

# Complexity
- **Time complexity**: $O(\text{m} \times \text{n})$ is the number of rows and (n) is the number of columns in the grid. We iterate over each possible `3x3` subgrid and check if it is a magic square.

- **Space complexity**: $O(1)$, aside from the input grid, as we use a constant amount of extra space to store the set of numbers and the sums.

# Code
```php
class Solution {
/**
* @param Integer[][] $grid
* @return Integer
*/
public static function numMagicSquaresInside($grid) {
$m = count($grid);
$n = count($grid[0]);
$res = 0;
if ($m < 3 || $n < 3) {
return 0;
}

for ($row = 0; $row <= $m - 3; $row++) {
for ($col = 0; $col <= $n - 3; $col++) {
$set = array_fill(0, 10, 0);
if (self::helper($grid, $row, $col, $set)) {
$res++;
}
}
}

return $res;
}

/**
* @param Integer[][] $grid
* @param Integer $row
* @param Integer $col
* @param Integer[] $set
* @return Boolean
*/
private static function helper($grid, $row, $col, &$set) {
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$val = $grid[$row + $i][$col + $j];
if ($val > 9 || $val < 1 || $set[$val] > 0) {
return false;
}
$set[$val]++;
}
}

$sum_row1 = $grid[$row][$col] + $grid[$row][$col + 1] + $grid[$row][$col + 2];
$sum_row2 = $grid[$row + 1][$col] + $grid[$row + 1][$col + 1] + $grid[$row + 1][$col + 2];
$sum_row3 = $grid[$row + 2][$col] + $grid[$row + 2][$col + 1] + $grid[$row + 2][$col + 2];

if ($sum_row1 != $sum_row2 || $sum_row1 != $sum_row3) {
return false;
}

$sum_col1 = $grid[$row][$col] + $grid[$row + 1][$col] + $grid[$row + 2][$col];
$sum_col2 = $grid[$row][$col + 1] + $grid[$row + 1][$col + 1] + $grid[$row + 2][$col + 1];
$sum_col3 = $grid[$row][$col + 2] + $grid[$row + 1][$col + 2] + $grid[$row + 2][$col + 2];

if ($sum_col1 != $sum_col2 || $sum_col1 != $sum_col3) {
return false;
}

$diag1 = $grid[$row][$col] + $grid[$row + 1][$col + 1] + $grid[$row + 2][$col + 2];
$diag2 = $grid[$row][$col + 2] + $grid[$row + 1][$col + 1] + $grid[$row + 2][$col];

if ($diag1 != $diag2) {
return false;
}

if ($sum_col1 != $sum_row1 || $sum_row1 != $diag1) {
return false;
}

return true;
}
}
```

If it can help you, please give me an upvote. Thank you so much for reading!
Binary file added medium/885. Spiral Matrix III/assets/img.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added medium/885. Spiral Matrix III/assets/img_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 7 additions & 3 deletions medium/885. Spiral Matrix III/description.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,23 @@ Return an array of coordinates representing the positions of the grid in the ord

Example 1:

![img.png](assets/img.png)

> **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0
>
> **Output:** [[0,0],[0,1],[0,2],[0,3]]
Example 2:

![img_1.png](assets/img_1.png)

> **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4
>
> **Output:** [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]

Constraints:

- 1 <= rows, cols <= 100
- 0 <= rStart < rows
- 0 <= cStart < cols
- `1 <= rows, cols <= 100`
- `0 <= rStart < rows`
- `0 <= cStart < cols`
8 changes: 5 additions & 3 deletions medium/885. Spiral Matrix III/solution-php.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ https://leetcode.com/problems/spiral-matrix-iii/solutions/5606322/solution-beat-

# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
- To traverse all the cells in a grid of size `rows * cols` starting from a specific position (`rStart`, `cStart`) in a spiral order, we can use an array of directions and a variable to keep track of the number of steps needed in each direction.
- To traverse all the cells in a grid of size `rows * cols` starting from a specific position (`rStart`, `cStart`) in spiral order, we can use an array of directions and a variable to keep track of the number of steps needed in each direction.
- We will move in sequential directions: **right, down, left, and up**, increasing the number of steps after every two directions (one complete cycle).

# Approach
Expand All @@ -17,11 +17,11 @@ https://leetcode.com/problems/spiral-matrix-iii/solutions/5606322/solution-beat-
- After every two directions, increment the number of steps required.

# Complexity
- Time complexity: **O(n×m)**
- Time complexity: $O(n \times m)$

We will traverse all cells in the grid once, so the time complexity is linear with respect to the number of cells in the grid, or `O(n×m)`, where `n` is the number of rows and `m` is the number of columns.

- Space complexity: **O(n×m)**
- Space complexity: $O(n \times m)$

The result array `ans` will contain all positions of the grid, so the space complexity is also linear with respect to the number of cells in the grid, or `O(n×m)`.

Expand Down Expand Up @@ -63,3 +63,5 @@ class Solution
}

```

If it can help you, please give me an upvote. Thank you so much for reading!

0 comments on commit c6cba75

Please sign in to comment.