classSolution: deffindMaxFish(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) defdfs(i: int, j: int) -> int: if i < 0or i >= m or j < 0or j >= n or grid[i][j] == 0: return0 s = grid[i][j] grid[i][j] = 0# 标记成访问过 for x, y in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1): s += dfs(x, y) # 四方向移动 return s returnmax(max(dfs(i, j) for j inrange(n)) for i inrange(m))
publicintfindMaxFish(int[][] grid) { this.grid = grid; intm= grid.length, n = grid[0].length, ans = 0; for (inti=0; i < m; ++i) for (intj=0; j < n; ++j) ans = Math.max(ans, dfs(i, j)); return ans; }
privateintdfs(int x, int y) { intm= grid.length, n = grid[0].length; if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0) return0; intsum= grid[x][y]; grid[x][y] = 0; // 标记成访问过 for (var d : DIRS) // 四方向移动 sum += dfs(x + d[0], y + d[1]); return sum; } }
classSolution { staticconstexprint dirs[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; public: intfindMaxFish(vector<vector<int>> &grid){ int m = grid.size(), n = grid[0].size(), ans = 0; function<int(int, int)> dfs = [&](int x, int y) -> int { if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0) return0; int sum = grid[x][y]; grid[x][y] = 0; // 标记成访问过 for (auto &d: dirs) // 四方向移动 sum += dfs(x + d[0], y + d[1]); return sum; }; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) ans = max(ans, dfs(i, j)); return ans; } };
var dirs = []struct{ x, y int }{ {-1, 0}, {1, 0}, {0, -1}, {0, 1} }
funcfindMaxFish(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) var dfs func(int, int)int dfs = func(x, y int)int { if x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0 { return0 } sum := grid[x][y] grid[x][y] = 0// 标记成访问过 for _, d := range dirs { // 四方向移动 sum += dfs(x+d.x, y+d.y) } return sum } for i := 0; i < m; i++ { for j := 0; j < n; j++ { ans = max(ans, dfs(i, j)) } } return }
funcmax(a, b int)int { if a < b { return b }; return a }