Created
January 28, 2025 19:02
-
-
Save tatsuyax25/4c8459a43a2743b91d40389aedec8c95 to your computer and use it in GitHub Desktop.
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 opera
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} grid | |
* @return {number} | |
*/ | |
var findMaxFish = function(grid) { | |
// Initialize the maximum fish count as 0 | |
let maxFish = 0; | |
// Get the number of rows and columns in the grid | |
const rows = grid.length; | |
const cols = grid[0].length; | |
// Helper function to perform DFS and count the fish | |
const dfs = (row, col) => { | |
// Base case: return 0 if out of bounds or the cell is land | |
if (row < 0 || col < 0 || row >= rows || col >= cols || grid[row][col] === 0) { | |
return 0; | |
} | |
// Collect the fish in the current cell | |
let fish = grid[row][col]; | |
// Mark the cell as visited by setting it to 0 | |
grid[row][col] = 0; | |
// Recursively collect fish from adjacent cells | |
let top = dfs(row + 1, col); | |
let down = dfs(row - 1, col); | |
let left = dfs(row, col - 1); | |
let right = dfs(row, col + 1); | |
// Return the total number of fish collected in this path | |
return fish + top + down + left + right; | |
} | |
// Loop through all the cells in the grid | |
for (let i = 0; i < rows; i++) { | |
for (let j = 0; j < cols; j++) { | |
// If it's a water cell with fish, perform DFS | |
if (grid[i][j] !== 0) { | |
maxFish = Math.max(dfs(i, j), maxFish); // Update the maximum fish count | |
} | |
} | |
} | |
// Return the maximum fish count | |
return maxFish; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment