岛屿最大面积

2024-10-01 11:40:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我参加了一个编码竞赛,我非常接近于解决下面的问题,但我的代码由于某种原因没有运行=(

以下是问题链接: https://leetcode.com/contest/leetcode-weekly-contest-53/problems/max-area-of-island/

我的解决方案:

class Solution(object):
 def maxAreaOfIsland(self, grid):
    """
    :type grid: List[List[int]]
    :rtype: int
    """
    self.longest = 0
    self.count = 0
    row = len(grid)
    col = len(grid[0])
    for i in range(row):
        for j in range(col):
            if grid[i][j] == 1:
                self.count += 1
                current = 1
                self.countIsland(i, j, current, grid)
    return self.longest
  def countIsland(self, k, z, current, grid):
    print(str(k) + "," + str(z) + "=" + str(current))
    grid[k][z] = -1
    if k > 0 and grid[k-1][z] == 1:
           return self.countIsland(k-1, z, current+1, grid)
    if k < (len(grid)-1) and grid[k+1][z] == 1:
           return self.countIsland(k+1, z, current+1, grid)
    if z > 0 and grid[k][z - 1] == 1:
           return self.countIsland(k, z-1, current+1, grid)
    if z < (len(grid[0])-1) and grid[k][z+1] == 1:
          return self.countIsland(k, z+1, current+1, grid)
    self.longest = max(self.longest, current)
    return current  

我1点下班,我得到5分而不是6分。如果您尝试在IDE中运行它,我的print语句将显示,对于递归的最后一次调用,current值正在被重新初始化,这不是我想要的。有什么想法为什么?在

谢谢!在


Tags: andselflenreturnlongestifdefcurrent
1条回答
网友
1楼 · 发布于 2024-10-01 11:40:26

基本方法是直观的。我们使用DFS在每个可能的位置扩展岛屿。当一个岛上的牢房被访问时,我们会“击沉”它。下面是我的Java实现,并通过了Leetcode上的所有测试。在

class Solution {
    private static final int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};

    public int maxAreaOfIsland(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    res = Math.max(res, dfs(grid, i, j));
                }
            }
        }
        return res;
    }

    private int dfs(int[][] grid, int x, int y) {
        if (grid[x][y] == 0) {
            return 0;
        }

        grid[x][y] = 0;
        int cnt = 1;
        for (int[] dir : dirs) {
            int nx = x + dir[0], ny = y + dir[1];
            if (nx >= 0 && nx < grid.length && ny >= 0 && ny < grid[0].length && grid[nx][ny] == 1) {
                cnt += dfs(grid, nx, ny);
            }
        }
        return cnt;
    }
} 

相关问题 更多 >