Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

002658 maximum number of fish in a grid #1238

Merged
merged 101 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
101 commits
Select commit Hold shift + click to select a range
c2ed436
Automated commit 1
mah-shamim Jan 28, 2025
f1b1d1a
Automated commit rollback 1
mah-shamim Jan 28, 2025
f5c05d2
Automated commit 2
mah-shamim Jan 28, 2025
a101f35
Automated commit rollback 2
mah-shamim Jan 28, 2025
e28e73b
Automated commit 3
mah-shamim Jan 28, 2025
152fde9
Automated commit rollback 3
mah-shamim Jan 28, 2025
fb0cfcc
Automated commit 4
mah-shamim Jan 28, 2025
620ecb9
Automated commit rollback 4
mah-shamim Jan 28, 2025
1a860db
Automated commit 5
mah-shamim Jan 28, 2025
6c694c9
Automated commit rollback 5
mah-shamim Jan 28, 2025
8f4db01
Automated commit 6
mah-shamim Jan 28, 2025
f4a7a92
Automated commit rollback 6
mah-shamim Jan 28, 2025
0a4b508
Automated commit 7
mah-shamim Jan 28, 2025
9dcbf52
Automated commit rollback 7
mah-shamim Jan 28, 2025
ce584a0
Automated commit 8
mah-shamim Jan 28, 2025
8b2036f
Automated commit rollback 8
mah-shamim Jan 28, 2025
10c491e
Automated commit 9
mah-shamim Jan 28, 2025
24d5088
Automated commit rollback 9
mah-shamim Jan 28, 2025
32c2307
Automated commit 10
mah-shamim Jan 28, 2025
17ad0f9
Automated commit rollback 10
mah-shamim Jan 28, 2025
1a15554
Automated commit 11
mah-shamim Jan 28, 2025
d289f65
Automated commit rollback 11
mah-shamim Jan 28, 2025
2aaaf87
Automated commit 12
mah-shamim Jan 28, 2025
7911425
Automated commit rollback 12
mah-shamim Jan 28, 2025
b1cab5e
Automated commit 13
mah-shamim Jan 28, 2025
3481b90
Automated commit rollback 13
mah-shamim Jan 28, 2025
c0edc12
Automated commit 14
mah-shamim Jan 28, 2025
c414d9f
Automated commit rollback 14
mah-shamim Jan 28, 2025
7e993e1
Automated commit 15
mah-shamim Jan 28, 2025
b2e9de6
Automated commit rollback 15
mah-shamim Jan 28, 2025
5fc7bfa
Automated commit 16
mah-shamim Jan 28, 2025
094f05d
Automated commit rollback 16
mah-shamim Jan 28, 2025
10012c5
Automated commit 17
mah-shamim Jan 28, 2025
8855b23
Automated commit rollback 17
mah-shamim Jan 28, 2025
cc5a7c9
Automated commit 18
mah-shamim Jan 28, 2025
f399950
Automated commit rollback 18
mah-shamim Jan 28, 2025
5ee5567
Automated commit 19
mah-shamim Jan 28, 2025
c396699
Automated commit rollback 19
mah-shamim Jan 28, 2025
0ab26b2
Automated commit 20
mah-shamim Jan 28, 2025
a66a9ac
Automated commit rollback 20
mah-shamim Jan 28, 2025
936ef1a
Automated commit 21
mah-shamim Jan 28, 2025
205765c
Automated commit rollback 21
mah-shamim Jan 28, 2025
6b81f3a
Automated commit 22
mah-shamim Jan 28, 2025
86442b0
Automated commit rollback 22
mah-shamim Jan 28, 2025
0c1651b
Automated commit 23
mah-shamim Jan 28, 2025
e7f2921
Automated commit rollback 23
mah-shamim Jan 28, 2025
7de6636
Automated commit 24
mah-shamim Jan 28, 2025
d0ebb96
Automated commit rollback 24
mah-shamim Jan 28, 2025
ba0baee
Automated commit 25
mah-shamim Jan 28, 2025
fef98c9
Automated commit rollback 25
mah-shamim Jan 28, 2025
06996da
Automated commit 26
mah-shamim Jan 28, 2025
e4e0f4d
Automated commit rollback 26
mah-shamim Jan 28, 2025
0db4d18
Automated commit 27
mah-shamim Jan 28, 2025
c29e80b
Automated commit rollback 27
mah-shamim Jan 28, 2025
45d97d5
Automated commit 28
mah-shamim Jan 28, 2025
e58084a
Automated commit rollback 28
mah-shamim Jan 28, 2025
56c3dc2
Automated commit 29
mah-shamim Jan 28, 2025
ba51ccb
Automated commit rollback 29
mah-shamim Jan 28, 2025
a36d485
Automated commit 30
mah-shamim Jan 28, 2025
05224af
Automated commit rollback 30
mah-shamim Jan 28, 2025
0727301
Automated commit 31
mah-shamim Jan 28, 2025
8dc3a05
Automated commit rollback 31
mah-shamim Jan 28, 2025
acec56c
Automated commit 32
mah-shamim Jan 28, 2025
7ef2db6
Automated commit rollback 32
mah-shamim Jan 28, 2025
331850d
Automated commit 33
mah-shamim Jan 28, 2025
512ab47
Automated commit rollback 33
mah-shamim Jan 28, 2025
bb28c69
Automated commit 34
mah-shamim Jan 28, 2025
0ccf03c
Automated commit rollback 34
mah-shamim Jan 28, 2025
8733307
Automated commit 35
mah-shamim Jan 28, 2025
09dcab6
Automated commit rollback 35
mah-shamim Jan 28, 2025
131f78d
Automated commit 36
mah-shamim Jan 28, 2025
a502ec3
Automated commit rollback 36
mah-shamim Jan 28, 2025
4d43ff9
Automated commit 37
mah-shamim Jan 28, 2025
c36d884
Automated commit rollback 37
mah-shamim Jan 28, 2025
fea7531
Automated commit 38
mah-shamim Jan 28, 2025
0cac92c
Automated commit rollback 38
mah-shamim Jan 28, 2025
a89c4e6
Automated commit 39
mah-shamim Jan 28, 2025
6080102
Automated commit rollback 39
mah-shamim Jan 28, 2025
488820e
Automated commit 40
mah-shamim Jan 28, 2025
e3557a5
Automated commit rollback 40
mah-shamim Jan 28, 2025
b776d91
Automated commit 41
mah-shamim Jan 28, 2025
fc31d04
Automated commit rollback 41
mah-shamim Jan 28, 2025
f5bb84f
Automated commit 42
mah-shamim Jan 28, 2025
4c1f004
Automated commit rollback 42
mah-shamim Jan 28, 2025
0dce2cc
Automated commit 43
mah-shamim Jan 28, 2025
f5b3d4f
Automated commit rollback 43
mah-shamim Jan 28, 2025
12872bf
Automated commit 44
mah-shamim Jan 28, 2025
af23071
Automated commit rollback 44
mah-shamim Jan 28, 2025
9e71f7a
Automated commit 45
mah-shamim Jan 28, 2025
1948b35
Automated commit rollback 45
mah-shamim Jan 28, 2025
cabeaf8
Automated commit 46
mah-shamim Jan 28, 2025
32fe244
Automated commit rollback 46
mah-shamim Jan 28, 2025
c09838c
Automated commit 47
mah-shamim Jan 28, 2025
2b5a5fe
Automated commit rollback 47
mah-shamim Jan 28, 2025
a5d8fb1
Automated commit 48
mah-shamim Jan 28, 2025
2f97385
Automated commit rollback 48
mah-shamim Jan 28, 2025
1449285
Automated commit 49
mah-shamim Jan 28, 2025
e187a5b
Automated commit rollback 49
mah-shamim Jan 28, 2025
7d7d40f
Automated commit 50
mah-shamim Jan 28, 2025
a8e193e
Automated commit rollback 50
mah-shamim Jan 28, 2025
f6310ae
#1236, #1237 leetcode problems 002658-maximum-number-of-fish-in-a-gri…
mah-shamim Jan 28, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 172 additions & 0 deletions algorithms/002658-maximum-number-of-fish-in-a-grid/README.md
mah-shamim marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
2658\. Maximum Number of Fish in a Grid

**Difficulty:** Medium

**Topics:** `Array`, `Depth-First Search`, `Breadth-First Search`, `Union Find`, `Matrix`

You are given a **0-indexed** 2D matrix `grid` of size `m x n`, where `(r, c)` represents:

- A **land** cell if `grid[r][c] = 0`, or
- A **water** cell containing `grid[r][c]` fish, if `grid[r][c] > 0`.

A fisher can start at any **water** cell `(r, c)` and can do the following operations any number of times:

- Catch all the fish at cell `(r, c)`, or
- Move to any adjacent **water** cell.

Return _the **maximum** number of fish the fisher can catch if he chooses his starting cell optimally, or `0` if no water cell exists_.

An **adjacent** cell of the cell `(r, c)`, is one of the cells `(r, c + 1)`, `(r, c - 1)`, `(r + 1, c)` or `(r - 1, c)` if it exists.

**Example 1:**

![example](https://assets.leetcode.com/uploads/2023/03/29/example.png)

- **Input:** grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]]
- **Output:** 7
- **Explanation:** The fisher can start at cell `(1,3)` and collect 3 fish, then move to cell `(2,3)` and collect 4 fish.

**Example 2:**

![example2](https://assets.leetcode.com/uploads/2023/03/29/example2.png)

- **Input:** grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]]
- **Output:** 1
- **Explanation:** The fisher can start at cells (0,0) or (3,3) and collect a single fish.



**Constraints:**

- `m == grid.length`
- `n == grid[i].length`
- `1 <= m, n <= 10`
- `0 <= grid[i][j] <= 10`


**Hint:**
1. Run DFS from each non-zero cell.
2. Each time you pick a cell to start from, add up the number of fish contained in the cells you visit.



**Solution:**

The problem is to find the maximum number of fish that a fisher can catch by starting at any water cell in a grid. The fisher can catch fish at the current cell and move to any adjacent water cell (up, down, left, or right) repeatedly.

### Key Points:
1. The grid contains cells that are either land (value `0`) or water (value > `0`).
2. The fisher can only move to adjacent water cells.
3. The objective is to find the maximum number of fish collectable, starting from the best possible water cell.

### Approach:
1. Use **Depth-First Search (DFS)** to explore all possible paths starting from each water cell.
2. For each unvisited water cell, run a DFS to calculate the total fish in the connected component.
3. Track the maximum fish collected from any connected component.

### Plan:
1. Initialize a 2D `visited` array to track whether a cell has been explored.
2. Iterate through each cell in the grid.
3. If the cell contains water and is not visited:
- Run a DFS starting from that cell.
- Accumulate the total fish in the connected water cells.
- Update the maximum fish collected so far.
4. Return the maximum fish count after exploring all cells.

Let's implement this solution in PHP: **[2658. Maximum Number of Fish in a Grid](https://github.com/mah-shamim/leet-code-in-php/tree/main/algorithms/002658-maximum-number-of-fish-in-a-grid/solution.php)**

```php
<?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function findMaxFish($grid) {
...
...
...
/**
* go to ./solution.php
*/
}

/**
* Helper function for DFS
* @param $r
* @param $c
* @param $grid
* @param $visited
* @param $rows
* @param $cols
* @param $directions
* @return array|bool|int|int[]|mixed|null
*/
function dfs($r, $c, &$grid, &$visited, $rows, $cols, $directions) {
...
...
...
/**
* go to ./solution.php
*/
}

// Example 1
grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]];
echo getMaxFish($grid); // Output: 7

// Example 2
$grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]];
echo getMaxFish($grid); // Output: 1
?>
```

### Explanation:

#### DFS Implementation:
- For each water cell `(r, c)`, recursively explore its neighbors if they are:
- Inside the grid boundaries.
- Unvisited.
- Water cells (value > 0).
- Accumulate the fish count during the recursion.

#### Steps:
1. Start from a water cell and mark it as visited.
2. Recursively visit its valid neighbors, adding up the fish count.
3. Return the total fish count for the connected component.

### Example Walkthrough:
#### Example Input:
```php
$grid = [
[0, 2, 1, 0],
[4, 0, 0, 3],
[1, 0, 0, 4],
[0, 3, 2, 0]
];
```

#### Execution:
1. Start at `(1, 3)` (value = 3). Run DFS:
- `(1, 3)` → `(2, 3)` (value = 4).
- Total fish = `3 + 4 = 7`.
2. Explore other water cells, but no connected component has a higher total fish count.
3. Output: `7`.

### Time Complexity:
- **DFS Traversal:** Each cell is visited once → O(m × n).
- **Overall Complexity:** O(m × n), where `m` and `n` are grid dimensions.

### Output for Examples:
- **Example 1:** `7`
- **Example 2:** `1`

The solution efficiently uses DFS to explore connected components of water cells and calculates the maximum fish catchable by a fisher starting from any water cell. This approach ensures optimal exploration and works well for the given constraints.

**Contact Links**

If you found this series helpful, please consider giving the **[repository](https://github.com/mah-shamim/leet-code-in-php)** a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
59 changes: 59 additions & 0 deletions algorithms/002658-maximum-number-of-fish-in-a-grid/solution.php
mah-shamim marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

class Solution {

/**
* @param Integer[][] $grid
* @return Integer
*/
function findMaxFish($grid) {
$rows = count($grid);
$cols = count($grid[0]);
$visited = array_fill(0, $rows, array_fill(0, $cols, false));

$directions = [
[-1, 0], // up
[1, 0], // down
[0, -1], // left
[0, 1] // right
];

$maxFish = 0;

for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
if ($grid[$i][$j] > 0 && !$visited[$i][$j]) {
$maxFish = max($maxFish, $this->dfs($i, $j, $grid, $visited, $rows, $cols, $directions));
}
}
}

return $maxFish;
}

/**
* Helper function for DFS
* @param $r
* @param $c
* @param $grid
* @param $visited
* @param $rows
* @param $cols
* @param $directions
* @return array|bool|int|int[]|mixed|null
*/
function dfs($r, $c, &$grid, &$visited, $rows, $cols, $directions) {
if ($r < 0 || $c < 0 || $r >= $rows || $c >= $cols || $grid[$r][$c] == 0 || $visited[$r][$c]) {
return 0;
}

$visited[$r][$c] = true;
$fishCount = $grid[$r][$c];

foreach ($directions as $dir) {
$fishCount += $this->dfs($r + $dir[0], $c + $dir[1], $grid, $visited, $rows, $cols, $directions);
}

return $fishCount;
}
}