leetcode-pp / 91alg-5-daily-check

91 天学算法第五期打卡
55 stars 14 forks source link

【Day 50 】2021-10-29 - 695. 岛屿的最大面积 #68

Open azl397985856 opened 3 years ago

azl397985856 commented 3 years ago

695. 岛屿的最大面积

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/max-area-of-island/

前置知识

暂无

题目描述

给定一个包含了一些 0 和 1 的非空二维数组 grid 。
一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,
这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。
你可以假设 grid 的四个边缘都被 0(代表水)包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 。)

示例 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]
对于上面这个给定矩阵应返回 6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1 。

示例 2:

[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0。

 
注意: 给定的矩阵grid 的长度和宽度都不超过 50
zhangyalei1026 commented 3 years ago

思路

用BFS做。

代码

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        # BFS 做

        visited = set([])
        ans = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):         
                if grid[i][j] and (i, j) not in visited :
                    visited.add((i, j))
                    queue = collections.deque([(i, j)])
                    area = 1
                    while queue:
                        cur_i, cur_j = queue.popleft()
                        # 如果queue中的4个邻居中有1,先看看这个1在不在visited里, 如果不在放入队列,加入visited
                        # 看看相邻的点 有没有1
                        if cur_i < len(grid) - 1 and grid[cur_i + 1][cur_j] == 1:
                            if (cur_i + 1, cur_j) not in visited:
                                area += 1
                                visited.add((cur_i + 1, cur_j))
                                queue.append((cur_i + 1, cur_j))
                        if cur_i > 0 and grid[cur_i - 1][cur_j] == 1:
                            if (cur_i - 1, cur_j) not in visited:
                                area += 1
                                visited.add((cur_i - 1, cur_j))
                                queue.append((cur_i - 1, cur_j))
                        if cur_j < len(grid[0]) - 1 and grid[cur_i][cur_j + 1] == 1:
                            if (cur_i, cur_j + 1) not in visited:
                                area += 1
                                visited.add((cur_i, cur_j + 1))
                                queue.append((cur_i, cur_j + 1))
                        if cur_j > 0 and grid[cur_i][cur_j - 1] == 1:
                            if (cur_i, cur_j - 1) not in visited:
                                area += 1
                                visited.add((cur_i, cur_j - 1))
                                queue.append((cur_i, cur_j - 1))
                    ans = max(ans, area)
        return ans
        # 代码写的太丑了,需要优化

复杂度分析

时间复杂度:O(mn) 矩阵大小 空间复杂度:O(mn)

watermelonDrip commented 3 years ago
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        stack = list()
        ans = 0
        for i,l in enumerate(grid):
            for j,k in enumerate(l):
                if grid[i][j] == 1:
                    tmp_res = 1
                    stack.append([i,j])
                    while stack:
                        x,y = stack.pop()
                        grid[x][y] = 0

                        for new_x, new_y in [ [x-1,y],[x+1,y],[x,y-1],[x,y+1]]:
                            if not 0<= new_x<len(grid) or not 0<= new_y<len(grid[0]):
                                continue
                            if grid[new_x][new_y] == 0:
                                continue
                            else:
                                tmp_res+=1
                                grid[new_x][new_y] = 0
                                stack.append([new_x,new_y])
                    ans = max(ans, tmp_res)
        return ans

用栈可以用递归

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        def dfs(grid,i,j):
            if 0<= i < m and 0<=j <n and grid[i][j] ==1:
                grid[i][j] = 0
                return 1+ dfs(grid,i+1,j)+ dfs(grid,i,j+1) +dfs(grid,i-1,j)+ dfs(grid,i,j-1)
            return 0

        ans = 0
        for i, l in enumerate(grid):
            for j , k in enumerate(l):
                if grid[i][j] == 1:
                    ans = max(dfs(grid,i,j),ans)
        return ans
HouHao1998 commented 3 years ago

思想

每次调用的时候默认num为1,进入后判断如果不是岛屿,则直接返回0,就可以避免预防错误的情况。 每次找到岛屿,则直接把找到的岛屿改成0,这是传说中的沉岛思想,就是遇到岛屿就把他和周围的全部沉默。 ps:如果能用沉岛思想,那么自然可以用朋友圈思想。有兴趣的朋友可以去尝试。

代码

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

        }

复杂度

siyuelee commented 3 years ago

dfs

class Solution(object):
    def maxAreaOfIsland(self, grid):
        def dfs(i, j):
            if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]):
                return 0
            if grid[i][j] == 0: return 0
            grid[i][j] = 0
            top = dfs(i + 1, j)
            right = dfs(i, j + 1)
            bottom = dfs(i - 1, j)
            left = dfs(i, j - 1)
            return 1 + sum([top, right, bottom, left])
        res = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                res = max(res, dfs(i, j))
        return res

T: O(mn) S: O(mn)

TimmmYang commented 3 years ago

思路

DFS,注意遍历过后就置为0,避免死循环。

代码

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        def dfs(row, col):
            if (0 <= row < m) and (0 <= col < n) and grid[row][col] == 1:
                grid[row][col] = 0 # 经过后就置为0,避免死循环
                return 1 + dfs(row+1, col) + dfs(row, col+1) + dfs(row-1, col) + dfs(row, col-1)
            else:
                return 0
        m, n = len(grid), len(grid[0])
        res = 0
        for i in range(m):
            for j in range(n):
                res = max(res, dfs(i, j))
        return res

复杂度

时间:O(mn) 空间:O(mn)

muimi commented 3 years ago

思路

DFS或BFS遍历求解

代码

Yufanzh commented 3 years ago

Intuition

BFS and DFS approach

Algorithm in python3

class Solution:
#     def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
#         #dfs approach
#         m = len(grid)
#         if m == 0:
#             return 0
#         n = len(grid[0])
#         ans = 0
#         def dfs(i,j):
#             #termination condition
#             if i < 0 or i >= m or j < 0 or j >= n:
#                 return 0
#             if grid[i][j] == 0:
#                 return 0
#             # inplace change to mark as visited
#             grid[i][j] = 0
#             #top
#             top = dfs(i-1, j)
#             #bottom
#             bottom = dfs(i+1, j)
#             #left
#             left = dfs(i, j-1)
#             #right
#             right = dfs(i, j+1)

#             #no need to change back to grid[i][j] = 1 as this will lead to repeated calculation
#             return 1 + sum([top, bottom, left, right])

#         for i in range(m):
#             for j in range(n):
#                 ans = max(ans, dfs(i,j))
#         return ans
     def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        #bfs approach
        m = len(grid)
        if m == 0:
             return 0
        n = len(grid[0])
        ans = 0
        DIR = [0, 1, 0, -1, 0]

        def bfs(i, j):
            ans = 0
            grid[i][j] = 0
            queue = deque([(i, j)])
            while queue:
                i, j = queue.popleft()
                ans += 1
                for c in range(4):
                    ni, nj = i + DIR[c], j + DIR[c+1]
                    if ni < 0 or ni >= m or nj < 0 or nj >= n or grid[ni][nj] == 0:
                        continue
                    grid[ni][nj] = 0 
                    queue.append((ni, nj))

            return ans

        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1:
                    ans = max(ans, bfs(i, j))
        return ans

Complexity Analysis

BpointA commented 3 years ago

思路

DFS

Python代码

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        m=len(grid)
        n=len(grid[0])
        visited=[[0]*n for i in range(m)]
        def dfs(i,j):

            if i<0 or j<0 or i>=m or j>=n:
                return 0
            if visited[i][j]==1:
                return 0
            visited[i][j]=1
            if grid[i][j]==0:
                return 0
            return 1+dfs(i+1,j)+dfs(i-1,j)+dfs(i,j+1)+dfs(i,j-1)
        ans=0
        for i in range(m):
            for j in range(n):            
                ans=max(ans,dfs(i,j))
        return ans

复杂度

时间:O(mn)

空间:O(mn)

Daniel-Zheng commented 3 years ago

思路

DFS。

代码(C++)

class Solution {
public:
    int dfs(vector<vector<int>>& grid, int row, int col) {
        if (row < 0 || col < 0 || row >= grid.size() || col >= grid[row].size() || grid[row][col] == 0) return 0;
        grid[row][col] = 0;
        int count = 1;
        count += dfs(grid, row + 1, col);
        count += dfs(grid, row - 1, col);
        count += dfs(grid, row, col + 1);
        count += dfs(grid, row, col - 1);
        return count;
    }

    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int res = 0;
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[i].size(); j++) {
                if (grid[i][j] == 1) res = max(res, dfs(grid, i, j));
            }
        }
        return res;
    }
};

复杂度分析

simonsayshi commented 3 years ago
class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {

        int maxArea = 0;
        for(int i = 0;i < grid.size();i++) {
            for(int j = 0;j < grid[0].size();j++) {
                if(grid[i][j] == 1) {
                    int tempArea = 0;
                    helper(grid, i, j, tempArea);
                    maxArea = max(maxArea,tempArea);                    
                }
            }
        }
        return maxArea;
    }

    void helper(vector<vector<int>>&M, int i , int j , int &tempArea) {
        if(i < 0 || i >= M.size() || j < 0 || j >= M[0].size() || M[i][j] == 0)
            return;
        tempArea++;
        M[i][j] = 0;
        helper(M, i + 1, j, tempArea);
        helper(M, i - 1, j, tempArea);
        helper(M, i, j + 1, tempArea);
        helper(M, i, j - 1, tempArea);
        return;
    }
};
KennethAlgol commented 3 years ago

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        int max = 0;
        for(int row = 0;row < grid.length;row++){
            for(int col = 0;col < grid[0].length;col++){
                if(grid[row][col] == 1){
                    max = Math.max(max, dfs(grid, new int[]{row, col}));
                }
            }
        }

        return max;
    }

    public int dfs(int[][] grid, int[] cell){
        if(cell[0] < 0 || cell[0] >= grid.length || cell[1] < 0 || cell[1] >= grid[0].length || grid[cell[0]][cell[1]] == 0){
            return 0;
        }

        grid[cell[0]][cell[1]] = 0;
        return 1 + dfs(grid, new int[]{cell[0] + 1, cell[1]}) + dfs(grid, new int[]{cell[0] - 1, cell[1]}) + dfs(grid, new int[]{cell[0], cell[1] + 1}) + dfs(grid, new int[]{cell[0], cell[1] - 1});
    }
}
learning-go123 commented 3 years ago

思路

代码

Go Code:


func maxAreaOfIsland(grid [][]int) int {
    m, n := len(grid), len(grid[0])
    var q [][2]int
    var res int
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            if grid[i][j] == 0 {
                continue
            }

            q = append(q, [2]int{i, j})
            grid[i][j] = 0
            count := 1
            for len(q) > 0 {
                x, y := q[0][0], q[0][1]
                for _, dir := range [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}} {
                    nx, ny := x+dir[0], y+dir[1]

                    // 检查边界
                    if nx < 0 || nx >= m || ny < 0 || ny >= n {
                        continue
                    }

                    // 检查是否走过
                    if grid[nx][ny] == 0 {
                        continue
                    }

                    q = append(q, [2]int{nx, ny})

                    // 置为0表示已经走过了
                    grid[nx][ny] = 0

                    count++
                }

                q = q[1:]
            }

            if count > res {
                res = count
            }
        }
    }
    return res
}

复杂度分析

令 n 为数组长度。

Laurence-try commented 3 years ago

思路

DFS

代码

使用语言:Python3

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        seen = set()
        def area(r, c):
            if not (0 <= r < len(grid) and 0 <= c < len(grid[0])
                    and (r, c) not in seen and grid[r][c]):
                return 0
            seen.add((r, c))
            return (1 + area(r+1, c) + area(r-1, c) +
                    area(r, c-1) + area(r, c+1))

        return max(area(r, c)
                   for r in range(len(grid))
                   for c in range(len(grid[0])))

复杂度分析 时间复杂度:O(row col) 空间复杂度:O(row col)

chen445 commented 3 years ago

代码

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        max_island=0
        row=len(grid)
        col=len(grid[0])
        for i in range(row):
            for j in range(col):
                part=grid[i][j]
                if part==1:
                    result=self.rec_island_size((i,j),grid)
                    max_island=max(max_island,result)
        return max_island

    def rec_island_size(self,pos,grid):
        if pos[0]>=len(grid) or pos[0]<0 or pos[1]>=len(grid[0]) or pos[1]<0 or grid[pos[0]][pos[1]]==0:
            return 0
        directions=[(0,1),(1,0),(-1,0),(0,-1)]
        grid[pos[0]][pos[1]]=0
        s=1
        for direction in directions:
            neighbor=(pos[0]+direction[0],pos[1]+direction[1])
            s+=self.rec_island_size(neighbor,grid)
        return s

复杂度

Time: O(m*n)

Space: O(m*n)

carsonlin9996 commented 3 years ago

思路

和LC200 一样用DFS或者BFS遍历整个grid, 用visited 和isValid来判定是否出界和跳过已判断过的格子

class Solution {

    int[] dX = new int[]{1, 0, -1, 0};
    int[] dY = new int[]{0, 1, 0, -1};
    public int maxAreaOfIsland(int[][] grid) {

        int m = grid.length;
        int n = grid[0].length;

        boolean[][] visited = new boolean[m][n];

        int maxArea = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (visited[i][j] || grid[i][j] == 0) {
                    continue;
                }
                maxArea = Math.max(bfsIsland(grid, i, j, visited), maxArea);
            }
        }

        return maxArea;

    }

    public int bfsIsland(int[][] grid, int x, int y, boolean[][] visited) {

        Queue<Position> queue = new ArrayDeque<>();

        queue.offer(new Position(x, y));
        visited[x][y] = true;

        int area = 0;

        while (!queue.isEmpty()) {

            Position curPos = queue.poll();
            if (grid[curPos.x][curPos.y] == 1) {
                area++;
            }

            for (int dir = 0; dir < 4; dir++) {
                int newX = curPos.x + dX[dir];
                int newY = curPos.y + dY[dir];

                if (!isValid(grid, newX, newY, visited)) {
                    continue;
                }
                queue.offer(new Position(newX, newY));
                visited[newX][newY] = true;
            }

        }
        return area;
    }

    private boolean isValid(int[][] grid, int x, int y, boolean[][] visited) {
        int m = grid.length;
        int n = grid[0].length;
        if (x < 0 || x >= m || y < 0 || y >= n) {
            return false;
        }
        if (grid[x][y] == 0) {
            return false;
        }
        return !visited[x][y];
    }
}

class Position {
    int x, y;

    Position (int x, int y) {
        this.x = x;
        this.y = y;
    }
}

DFS 类似 若是x,y不符合判定条件如出边界, visited, 或者grid[x][y] != 1, 则return, 否者用curArea++ 来把每次递归的和加起来

class Solution {

    int[] dX = new int[]{1, 0, -1, 0};
    int[] dY = new int[]{0, 1, 0, -1};

    public int maxAreaOfIsland(int[][] grid) {

        int m = grid.length;
        int n = grid[0].length;

        int maxArea = 0;
        boolean[][] visited = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (visited[i][j] || grid[i][j] == 0) {
                    continue;
                }
                int curArea[] = new int[1];
                dfsIsland(grid, i, j, visited, curArea);

                maxArea = Math.max(curArea[0], maxArea);
            }
        }

        return maxArea;

    }

    public void dfsIsland(int[][] grid, int x, int y, boolean[][] visited, int[] curArea) {
        if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || visited[x][y] || grid[x][y] == 0) {
            return;
        }

        visited[x][y] = true;
        curArea[0]++;
        for (int dir = 0; dir < 4; dir++) {    
            dfsIsland(grid, x + dX[dir], y + dY[dir], visited, curArea);
        }

    }
}

TC: O(MN)/ SC: O(MN)

hengistchan commented 3 years ago

···cpp class Solution { public int maxAreaOfIsland(int[][] grid) { int max = 0; for(int i = 0; i < grid.length; i++){ for(int j = 0; j < grid[0].length; j++){ if(grid[i][j] == 1){ max = Math.max (dfs(grid, i, j), max); } } } return max; } int dfs(int[][] grid, int i, int j){ if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0){ return 0; } grid[i][j] = 0; int count = 1; count += dfs(grid, i+1, j); count += dfs(grid, i-1, j); count += dfs(grid, i, j+1); count += dfs(grid, i, j-1); return count; } }

xy147 commented 3 years ago

思路

DFS

js代码

var maxAreaOfIsland = function(grid) {
  const row = grid.length, col = grid[0].length
  let res = 0
  const DFS = (i, j) => {
    if (i < 0 || i >= row || j < 0 || j >= col) {
      return 0
    }
    if(grid[i][j] == 0) {return 0}
    grid[i][j] = 0
    return 1 + DFS(i, j-1) + DFS(i-1, j) + DFS(i, j+1) + DFS(i+1, j)
  }

  for(let i=0; i<row; i++) {
    for(let j=0; j<col; j++) {
      if (grid[i][j] == 1) {
        res = Math.max(res, DFS(i,j))
      } else {
        continue
      }
    }
  }
  return res
};

复杂度分析

ai2095 commented 3 years ago

695. Max Area of Island

https://leetcode.com/problems/max-area-of-island/

Topics

思路

DFS

代码 Python

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        result = 0
        def dfs(r:int, c:int) -> int:
            nonlocal grid
            if r<0 or r== len(grid) or c<0 or c==len(grid[0]) or grid[r][c] == 0:
                return 0
            grid[r][c] = 0
            count = 1
            directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
            for d in directions:
                cur_r, cur_c = r + d[0], c + d[1]
                count += dfs(cur_r, cur_c)
            return count

        for r in range(len(grid)):
            for c in range(len(grid[0])):
                if grid[r][c] == 1:
                    result = max(result, dfs(r, c))
        return result

复杂度分析

时间复杂度: O(RC)
空间复杂度:O(R
C)

asterqian commented 3 years ago

思路

Loop through very land if it has a value of 1, mark it to 0 once stepped on it to avoid having an addition visited hashset. Then go through the 4 directions to gather the island area.

代码

int dfs(vector<vector<int>>& grid, int i, int j, int rowLimit, int colLimit) {
    if (i < 0 || i >= rowLimit || j < 0 || j >= colLimit) return 0;
    if (grid[i][j] == 0) return 0;
    grid[i][j] = 0; // avoid repeated counting
    return 1 + dfs(grid, i - 1, j, rowLimit, colLimit) + dfs(grid, i + 1, j, rowLimit, colLimit) 
           + dfs(grid, i, j - 1, rowLimit, colLimit) + dfs(grid, i, j + 1, rowLimit, colLimit); // go through 4 directions
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
    int maxVal = 0;
    for (int row = 0; row < grid.size(); row++) {
        for (int col = 0; col < grid[0].size(); col++) {
            maxVal = max(maxVal, dfs(grid, row, col, grid.size(), grid[0].size()));
        }
    }
    return maxVal;
}

Time Complexity: O(mn) grid row * col

Space Complexity: O(mn) grid row * col

zhiyuanpeng commented 3 years ago
class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:

        def dfs(i, j):
            count = 0
            if 0 <= i < m and 0 <= j < n and grid[i][j] == 1:
                grid[i][j] = 2
                count += 1
                return count + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1)
            else:
                return 0

        m, n = len(grid), len(grid[0])
        max_count = 0
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == 1:
                    count = dfs(i, j)
                    max_count = max(count, max_count)
        return max_count
zol013 commented 3 years ago

BFS, DFS

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:

        rows = len(grid)
        cols = len(grid[0])
        max_area = 0

        def dfs(r, c, curr_area):
            if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] == 0:
                return 0
            grid[r][c] = 0
            return 1 + dfs(r,c+1,curr_area) + dfs(r,c-1,curr_area) + dfs(r+1,c,curr_area)+ dfs(r-1,c,curr_area)

        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    curr_area = dfs(r, c, 0)
                    max_area = max(curr_area, max_area)
        return max_area

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:       
        rows =  len(grid)
        cols = len(grid[0])
        max_area = 0
        directions = [(1,0),(-1,0),(0,1),(0,-1)]

        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    grid[r][c] = 0
                    curr_area = 1
                    neighbors = deque([(r,c)])
                    while neighbors:
                        row, col = neighbors.popleft()
                        for row_diff, col_diff in directions:
                            new_row = row + row_diff
                            new_col = col + col_diff
                            if not (0 <= new_row < rows and 0 <= new_col < cols): continue
                            if grid[new_row][new_col] == 0:
                                continue
                            curr_area += 1
                            grid[new_row][new_col] = 0
                            neighbors.append((new_row, new_col))
                    max_area = max(max_area, curr_area)
        return max_area

TC:O(row col) SC: O(row col)

ginnydyy commented 3 years ago

Problem

https://leetcode.com/problems/max-area-of-island/

Notes

Solution

Complexity

jaysonss commented 3 years ago

思路

使用DFS,对已经访问过的节点修改值为0

代码

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        if(grid.length==0)return 0;
        int max = 0;

        for(int row = 0;row<grid.length;row++){
            for(int col = 0;col<=grid[0].length;col++){
                max = Math.max(max,dfs(row,col,grid));
            }
        }
        return max;
    }

    int dfs(int row,int col, int[][] matrix){
        if(row<0 || col<0 || row>=matrix.length || col>=matrix[0].length || matrix[row][col] == 0)return 0;
        int ans = 1;
        matrix[row][col]=0;
        for(int i=-1;i<=1;i+=2){
            ans += dfs(row+i,col,matrix);
            ans += dfs(row,col+i,matrix);
        }
        return ans;
    }
}
XinnXuu commented 3 years ago

思路

DFS,向上下左右四个方向探索土地,非土地返回0,是土地返回1。为了防止重复访问,已访问过的土地修改值为0。

代码

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

复杂度

mannnn6 commented 3 years ago

代码

class Solution {
    private int n, m;
    private int[][] g;
    private int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
    public int dfs(int x, int y) 
    {
        int area = 1;
        g[x][y] = 0; 
        for(int i = 0; i < 4; i++)
        {
            int a = x + dx[i], b = y + dy[i];

            if(a >=0 && a < n && b >= 0 && b < m && g[a][b] != 0)
                area += dfs(a, b);
        }      
        return area; 
    }
    public int maxAreaOfIsland(int[][] grid) {
        g = grid;
        int res = 0;
        n = grid.length; m = grid[0].length;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                if(g[i][j] != 0)
                    res = Math.max(res,dfs(i,j));
        return res;  
    }
}

复杂度

时间复杂度:O(row column) 空间复杂度:O(row column)

jiahui-z commented 3 years ago

思路: depth first search, iterate through the grid, for each cell we check all its neighbors recursively

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        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, areaOfIsland(grid, i, j));
                }
            }
        }
        return res;
    }

    private int areaOfIsland(int[][] grid, int i, int j) {
        if (i >= 0 && i < grid.length && j >= 0 && j < grid[0].length && grid[i][j] == 1) {
            grid[i][j] = 0;
            return 1 + areaOfIsland(grid, i - 1, j) + areaOfIsland(grid, i + 1, j) + areaOfIsland(grid, i, j - 1) + areaOfIsland(grid, i, j + 1);
        }
        return 0;
    }
}

Time complexity: O(mn) Space complexity: O(mn)

leungogogo commented 3 years ago
class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        boolean seen[][] = new boolean[m][n];

        Deque<int[]> stack = new LinkedList<>();
        int maxArea = 0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1 && !seen[i][j]) {
                    // dfs
                    int area = 0;
                    stack.push(new int[] {i, j});
                    while (!stack.isEmpty()) {
                        int elem[] = stack.pop();
                        int r = elem[0], c = elem[1];
                        if (r < 0 || c < 0 || r >= m || c >= n || seen[r][c] || grid[r][c] == 0) {
                            continue;
                        }

                        seen[r][c] = true;
                        ++area;
                        stack.push(new int[] {r - 1, c});
                        stack.push(new int[] {r + 1, c});
                        stack.push(new int[] {r, c - 1});
                        stack.push(new int[] {r, c + 1});
                    }
                    maxArea = Math.max(maxArea, area);
                }
            }
        }
        return maxArea;
    }
}
falconruo commented 3 years ago

思路:

  1. 深度优先遍历,岛屿的面积是累加的,总和为以当前节点为根的树的所有节点
  2. 广度优先遍历,每次检查4个相邻的位置是否为1,并将相邻为1的节点放入辅助队列中

复杂度分析:

代码(C++):

class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        if (grid.empty()) return 0;

        int m = grid.size();
        int n = grid[0].size();

        int res = 0;
        for (int y = 0; y < m; ++y)
            for (int x = 0; x < n; ++x)
                if (grid[y][x] == 1)
                    res = max(res, dfs(grid, y, x));
        return res;
    }

private:
    int dfs(vector<vector<int>>& grid, int y, int x) {
        if (y >= grid.size() || y < 0 || x >= grid[0].size() || x < 0 || grid[y][x] != 1) return 0;

        int count = 1;
        grid[y][x] = 2;

        count += dfs(grid, y + 1, x);
        count += dfs(grid, y - 1, x);
        count += dfs(grid, y, x + 1);
        count += dfs(grid, y, x - 1);

        return count;
    }
};
RonghuanYou commented 3 years ago
class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        if not grid:
            return 

        def dfs(i, j):
            if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0:
                return 0
            grid[i][j] = 0
            res = 1
            for x, y in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                res += dfs(i + x, j + y)
            return res

        res = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                cur = dfs(i, j)
                res = max(cur, res)
        return res
yj9676 commented 3 years ago
class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        int ans = 0;
        for (int i = 0; i != grid.length; ++i) {
            for (int j = 0; j != grid[0].length; ++j) {
                ans = Math.max(ans, dfs(grid, i, j));
            }
        }
        return ans;
    }

    public int dfs(int[][] grid, int cur_i, int cur_j) {
        if (cur_i < 0 || cur_j < 0 || cur_i == grid.length || cur_j == grid[0].length || grid[cur_i][cur_j] != 1) {
            return 0;
        }
        grid[cur_i][cur_j] = 0;
        int[] di = {0, 0, 1, -1};
        int[] dj = {1, -1, 0, 0};
        int ans = 1;
        for (int index = 0; index != 4; ++index) {
            int next_i = cur_i + di[index], next_j = cur_j + dj[index];
            ans += dfs(grid, next_i, next_j);
        }
        return ans;
    }
}
ysy0707 commented 3 years ago

思路:DFS

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        int res = 0;
        for(int r = 0; r < grid.length; r++){
            for(int c = 0; c < grid[0].length; c++){
                if(grid[r][c] == 1){
                    int a = dfs(grid, r, c);
                    res = Math.max(res, a);
                }
            }
        }
        return res;
    }

    public int dfs(int[][] grid, int r, int c){
        // 如果这个格子超过界限,直接返回
        if(!inArea(grid, r, c)){
            return 0;
        }
        // 如果这个格子不是岛屿,直接返回
        if(grid[r][c] != 1){
            return 0;
        }
        // 将格子标记为「已遍历过」
        grid[r][c] = 2;
        //每遍历到一个格子,就把面积加一
        // 访问上、下、左、右四个相邻结点
        return 1
            + dfs(grid, r - 1, c)
            + dfs(grid, r + 1, c)
            + dfs(grid, r, c - 1)
            + dfs(grid, r, c + 1);
    }
    // 判断坐标 (r, c) 是否在网格中
    public boolean inArea(int[][] grid, int r, int c){
        return 0 <= r && r < grid.length && 0 <= c && c < grid[0].length;
    }
}

时间复杂度:O(N^2) 空间复杂度:O(N^2)

15691894985 commented 3 years ago

【day50】695. 岛屿的最大面积

https://leetcode-cn.com/problems/max-area-of-island/

思路:

def maxAresOfIsland(grid):
    m = len(grid)
    if m ==0 :
        return 0
    n = len(grid[0])
    ans = 0 #记录面积
    def dfs(i,j):#i,j是数组行列 ,每个点的上下左右
        if i < 0 or i >= m or j < 0 or j >= n:
            return 0
        if grid[i][j]==0:
            return 0
        grid[i][j] = 0
        top = dfs(i+1,j)
        bottom = dfs(i-1,j)
        left = dfs(i,j-1)
        right = dfs(i,j+1)
        return 1+sum([top, bottom, left, right])
    for i in range(m):
        for j in range(n):
            ans = max(ans,dfs(i,j))
    return ans

复杂度:

m-z-w commented 3 years ago
var maxAreaOfIsland = function(grid) {
    const height = grid.length
    const width = grid[0].length
    let maxArea = 0
    for (let i = 0; i < height; i++) {
        for (let j = 0; j < width; j++) {
            if (grid[i][j] === 1) {
                const area = dfs(grid, i, j)
                if (area > maxArea) {
                    maxArea = area
                }
            }   
        }
    }
    return maxArea
};
const dfs = (grid, i, j) => {
    const height = grid.length
    const width = grid[0].length
    let area = 1
    if (i < 0 || j < 0 || i >= height || j >= width || grid[i][j] !== 1) {
        return 0
    }
    grid[i][j] = 0
    area += dfs(grid, i + 1, j)
    area += dfs(grid, i - 1, j)
    area += dfs(grid, i, j + 1)
    area += dfs(grid, i, j - 1)
    return area
}

时间:O(n m) 空间:O(n m)

peteruixi commented 3 years ago

思路

遍历每个位置以每个位置为出发点去dfs dfs返回所构成岛屿的大小, 用result存储最大值

代码

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        m,n = len(grid), len(grid[0])
        def dfs(i, j):
            while 0<=i<m and 0<=j<n and grid[i][j]:
                grid[i][j]=0
                return 1+dfs(i+1,j)+dfs(i-1,j)+dfs(i,j+1)+dfs(i,j-1)
            else:
                return 0 
        result = 0
        for x in range(m):
            for y in range(n):
                result = max(dfs(x,y),result)
        return result

复杂度分析

last-Battle commented 3 years ago

思路

关键点

代码

C++ Code:


class Solution {
public:
    int xx[4] = {0, 0, 1, -1};
    int yy[4] = {1, -1, 0, 0};

    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int res = 0;

        for (int i = 0; i < grid.size(); ++i) {
            for (int j = 0; j < grid[0].size(); ++j) {
                if (grid[i][j] == 1) {
                    int temp = 0;
                    helper(grid, i, j, temp);
                    res = max(res, temp);
                }
            }
        }

        return res;
    }

    void helper(vector<vector<int>>& grid, int x, int y, int& res) {
        if (!isValid(grid, x, y) || grid[x][y] == 0) {
            return;
        }

        if (grid[x][y] == 1) {
            res += 1;
            grid[x][y] = 0;
        }

        for (int i = 0; i < 4; ++i) {
            int tx = x + xx[i];
            int ty = y + yy[i];
            helper(grid, tx, ty, res);
        }
    }

    bool isValid(vector<vector<int>>& grid, int x, int y) {
        return !(x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size());
    }
};

复杂度分析

令 n 为数组长度。

chun1hao commented 3 years ago
var maxAreaOfIsland = function (grid) {
  let row = grid.length;
  let col = grid[0].length;
  let dfs = (i, j) => {
    if (i < 0 || i >= row || j < 0 || j >= col) return 0;
    if (!grid[i][j]) return 0;
    grid[i][j] = 0;
    return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j + 1) + dfs(i, j - 1);
  };

  let ans = 0;
  for (let i = 0; i < row; i++) {
    for (let j = 0; j < col; j++) {
      ans = Math.max(ans, dfs(i, j));
    }
  }
  return ans;
};
L-SUI commented 3 years ago
var maxAreaOfIsland = function(grid) {
  const row = grid.length, col = grid[0].length
  let res = 0
  const DFS = (i, j) => {
    // 下标越界返回0
    if (i < 0 || i >= row || j < 0 || j >= col) {
      return 0
    }
    // 值为0返回0
    if(grid[i][j] == 0) {return 0}
    // 访问过后置为0,防止重复访问
    grid[i][j] = 0
    // 递归计算岛屿面积
    return 1 + DFS(i, j-1) + DFS(i-1, j) + DFS(i, j+1) + DFS(i+1, j)
  }
  // 遍历二维数组
  for(let i=0; i<row; i++) {
    for(let j=0; j<col; j++) {
      if (grid[i][j] == 1) {
        res = Math.max(res, DFS(i,j))
      } else {
        continue
      }
    }
  }
  return res
};
carterrr commented 3 years ago
class Solution {
    final int[][] moves = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
    public int maxAreaOfIsland(int[][] grid) {
        int row = grid.length, 
        col = grid[0].length,
        max = 0;
        boolean[][] visited = new boolean[row][col];
        for(int i = 0; i< row; i++) {
            for(int j = 0; j < col; j++) {
                if(visited[i][j]) continue;
                if(grid[i][j] == 0){
                    visited[i][j] = true;
                    continue;
                } 
                max = Math.max(max, dfs(grid, i, j, visited));
            }
        }
        return max;
    }

    private int dfs(int[][] grid, int i ,int j, boolean[][] visited) {
        int area = 0;
        if(grid[i][j] == 0) {
            visited[i][j] = true;
            return area;
        }
        visited[i][j] = true;
        area += 1;
        for(int k = 0; k< 4; k++){
            int ni = i + moves[k][0];
            int nj = j + moves[k][1];
            if(ni >=0 && ni < grid.length && nj >=0 && nj < grid[0].length && !visited[ni][nj]) {
               area += dfs(grid, ni, nj, visited); 
            }
        } 
        return area;
    }
}
hewenyi666 commented 3 years ago

题目名称

695. 岛屿的最大面积

题目链接

https://leetcode-cn.com/problems/max-area-of-island/

题目思路

参考题解

借用图像渲染的深度搜索的思路,将其队列算法包装为一个函数,进行遍历,当统计到岛屿时则调用函数,每次统计完则将岛屿消灭,同时将该岛屿的大小计入列表,最后返回列表中的最大值

code for Python3

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        n,m=len(grid),len(grid[0])#n为纵长,m为横长
        length=[]
        def que(sr,sc):
            num=1
            que=collections.deque([(sr,sc)])
            grid[sr][sc]=0
            while que:
                x,y=que.popleft()
                for mx,my in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]:
                    if 0<=mx<n and 0<=my<m and grid[mx][my]==1:
                        que.append((mx,my))
                        num=num+1
                        grid[mx][my]=0
            length.append(num)
        for h in range(n):
            for w in range(m):
                if(grid[h][w]==1):
                    que(h,w)
        if(len(length)==0):
            return 0
        else:
            return max(length)

复杂度分析

falsity commented 3 years ago

思路:通过DFS求每个岛屿的面积,然后不断更新最大岛屿的面积

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        if(grid.length == 0 || grid[0].length == 0){
            return 0;
        }
        return dfs(grid);
    }

    private int dfs(int[][] grid){
        int m = grid.length;
        int n = grid[0].length;
        int count = 0;
        int maxSize = 0;
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == 0){
                    continue;
                }else{
                    count++;
                    System.out.println(i + "," + j + "," + count);
                    maxSize = Math.max(maxSize, search(i, j, grid));
                }
            }
        }
        return maxSize;

    }

    private int search(int i, int j, int[][] grid){
        int size = 0;
        //base case
        if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || 
            grid[i][j] == 0){
            return 0;
        }else{
            grid[i][j] = 0;
            size++;
            size += search(i - 1, j, grid);
            size += search(i + 1, j, grid);
            size += search(i, j - 1, grid);
            size += search(i, j + 1, grid);
        }
        return size;
    }
}

时间复杂度:O(M*N) 每个点都要遍历

空间复杂度:O(MN) 最坏情况岛屿面积为M N

V-Enzo commented 3 years ago

思路

先插个眼

class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int maxArea=0;
        for(int i=0;i<grid.size();i++){
            for(int j=0;j<grid[0].size();j++){
                if(grid[i][j]==1){                   
                    maxArea=max(assist(i,j,grid),maxArea);
                }
            }
        }
        return maxArea;      
    }
    int assist(int i,int j,vector<vector<int>>& grid){
        if(i<0||i>=grid.size()||j<0||j>=grid[0].size()||grid[i][j]==0) return 0;
        grid[i][j]=0;
        return 1+assist(i-1,j,grid)+assist(i+1,j,grid)+assist(i,j-1,grid)+assist(i,j+1,grid);
    }
};
goddessIU commented 3 years ago

抱歉,由于我在五十天才加入,所以估计很难跟上进度了,所以我只能先去学习之前的内容了,所以我的打卡没法是新的题目,我会自己发以前题目的打卡

第29天找到小镇法官

思路: 我目前也没有学到bfs和dfs,直观想法就是把这个图以邻接矩阵形式存储,再用for循环找到法官

/**
 * @param {number} n
 * @param {number[][]} trust
 * @return {number}
 */
var findJudge = function(n, trust) {
    const total = [];
    const rev = [];
    if(n == 1){
        return 1;
    }
    for(const [a,b] of trust) {
        if(!total[b]) {
            total[b] = [];
        }
        if(!rev[a]) {
            rev[a] = [];
        }
        total[b].push(a);
        rev[a].push(b);
    }
    for(let i = 1;i<=n;i++) {
        if(total[i]&&total[i].length===n-1&&!rev[i]) {
            return i;
        }
    }
    return -1;
};

时间复杂度:O(n2)
空间复杂度:O(n
2)

chaggle commented 3 years ago

title: "Day 50 695. 岛屿的最大面积" date: 2021-10-29T22:42:28+08:00 tags: ["Leetcode", "c++", "traceback"] categories: ["91-day-algorithm"] draft: true


695. 岛屿的最大面积

题目

给你一个大小为 m x n 的二进制矩阵 grid 。

岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。

岛屿的面积是岛上值为 1 的单元格的数目。

计算并返回 grid 中最大的岛屿面积。如果没有岛屿,则返回面积为 0 。

 

示例 1:

输入:grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
输出:6
解释:答案不应该是 11 ,因为岛屿只能包含水平或垂直这四个方向上的 1 。
示例 2:

输入:grid = [[0,0,0,0,0,0,0,0]]
输出:0
 

提示:

m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j] 为 0 或 1

题目思路

  • 1、dfs常规解法,但是题目中dfs在main函数内递归,局部变量不能重名,重名会导致错误!
  • 2、本题由于题目设置是岛屿并使用0 或 1 表示,故可以不设置访问数组,一般dfs需要设置bool类型的访问数组来表示是否访问此单位。
class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int ans = 0;
        int n = grid.size(), m = grid[0].size();
        for(int i = 0; i < grid.size(); ++i)
        {
            for(int j = 0; j < grid[0].size(); ++j)
            {
                if (grid[i][j] == 1) ans = max(dfs(grid, i, j), ans);
            }
        }
        return ans;
    }

    int dfs(vector<vector<int>>& grid, int i, int j)
    {
        int ans = 0;
        int l = grid.size(), r = grid[0].size();
        if(i >= l || i < 0 || j >= r || j < 0 || grid[i][j] == 0) return 0;
        else
        {
            ans++;
            grid[i][j] = 0;
            ans += dfs(grid, i + 1, j);
            ans += dfs(grid, i, j + 1);
            ans += dfs(grid, i - 1, j);
            ans += dfs(grid, i, j - 1);
        }

        return ans;
    }
};

复杂度

Weisday commented 3 years ago

先留个坑

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        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) {
                    int a = area(grid, i, j);
                    res = Math.max(res, a);
                }
            }
        }
        return res;
    }

    int area(int[][] grid, int i, int j) {
        if (!inArea(grid, i, j)) {
            return 0;
        }
        if (grid[i][j] != 1) {
            return 0;
        }
        grid[i][j] = 2;

        return 1 
            + area(grid, i - 1, j)
            + area(grid, i + 1, j)
            + area(grid, i, j - 1)
            + area(grid, i, j + 1);
    }

    boolean inArea(int[][] grid, int i, int j) {
        return 0 <= i && i < grid.length 
            && 0 <= j && j < grid[0].length;
    }
}
machuangmr commented 3 years ago

题目695. 岛屿的最大面积

思路

Jinjin680 commented 3 years ago

思路

代码

class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        if(!grid.size()) return 0;
        int res = 0;
        for(int i = 0; i < grid.size(); i++){
            for(int j = 0; j < grid[0].size(); j++){
                if(grid[i][j] == 1){
                    int t = dfs(grid, i, j);
                    res = max(res, t);
                }
            }
        }
        return res;
    }
    int dfs(vector<vector<int>>& grid, int i, int j){
        if(i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() || !grid[i][j])
            return 0;
        grid[i][j] = 0;
        return(1 + dfs(grid, i+1, j) + dfs(grid, i, j+1) + dfs(grid, i-1, j) + dfs(grid, i, j-1));
    }
};

复杂度分析

newbeenoob commented 3 years ago

思路


与岛屿数量那道题基本雷同,二维平面上的DFS/BFS 即可,这类题目的一个小技巧是可以设置一个dx , dy 方向数组,方便模拟每一步上下左右的行动;在遍历的时候一定要标记已访问的区域,防止走回头路,这里可以直接在原网格数组上修改(即沉岛)

代码:JavaScript

使用二维数组:

var maxAreaOfIsland = function(grid) {

    const rows = grid.length , cols = grid[0].length;

    if (!rows || !cols) return 0;
    // 方向数组
    const deltaX = [1 , -1 , 0 , 0];
    const deltaY = [0 , 0 , -1 , 1];

    let ans = 0;

    const inArea = (r , c , rows , cols) => {
        return r >= 0 && r < rows && c >= 0 && c < cols;
    }

    const dfs = (grid , r , c , rows , cols) => {
        let sum = grid[r][c];
        grid[r][c] = 0; // 沉岛

        let nr , nc;
        for (let i = 0 ; i < 4 ; ++i) {
            nr = r + deltaX[i];
            nc = c + deltaY[i];
            if (inArea(nr , nc , rows , cols) && grid[nr][nc] === 1) {
                sum += dfs(grid , nr , nc , rows , cols);
            }
        }

        return sum;
    }

    for(let r = 0 ; r < rows ; ++r) {
        for(let c = 0 ; c < cols ; ++c){
            if (grid[r][c] === 1) {
                ans = Math.max(ans , dfs(grid , r , c , rows , cols));
            }
        }
    }

    return ans;
};

复杂度分析


标签


深度优先搜索

AgathaWang commented 3 years ago

先马后看

class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        m = len(grid)
        if m == 0: return 0
        n = len(grid[0])
        ans = 0
        def dfs(i, j):
            if i < 0 or i >= m or j < 0 or j >= n: return 0
            if grid[i][j] == 0: return 0
            grid[i][j] = 0
            top = dfs(i + 1, j)
            bottom = dfs(i - 1, j)
            left = dfs(i, j - 1)
            right = dfs(i, j + 1)
            return 1 + sum([top, bottom, left, right])
        for i in range(m):
            for j in range(n):
                ans = max(ans, dfs(i, j))
        return ans
joriscai commented 3 years ago

思路

代码

javascript

/*
 * @lc app=leetcode.cn id=695 lang=javascript
 *
 * [695] 岛屿的最大面积
 */

// @lc code=start
/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxAreaOfIsland = function(grid) {
  let ret = 0
  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid[0].length; j++) {
      ret = Math.max(ret, dfs(grid, i, j))
    }
  }

  return ret
};

function dfs(grid, i, j) {
  // 越界了
  if (i < 0 || j < 0 || i === grid.length || j === grid[0].length) {
    return 0
  }

  // 无土地
  if (grid[i][j] === 0) {
    return 0
  }

  // 有土地,但访问过要将土地置零,避免下面重复判断
  grid[i][j] = 0
  const top = dfs(grid, i + 1, j)
  const bottom = dfs(grid, i - 1, j)
  const left = dfs(grid, i, j - 1)
  const right = dfs(grid, i, j + 1)

  return 1 + left + right + top + bottom
}
// @lc code=end

复杂度分析

Cartie-ZhouMo commented 3 years ago
class Solution:
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        ans = 0

        def dfs(i, j):
            if i < 0 or i >= m or j < 0 or j >= n: return 0
            if grid[i][j] == 0: return 0
            grid[i][j] = 0
            top = dfs(i + 1, j)
            bottom = dfs(i - 1, j)
            left = dfs(i, j - 1)
            right = dfs(i, j + 1)
            return 1 + sum([top, bottom, left, right])

        for i in range(m):
            for j in range(n):
                ans = max(ans, dfs(i, j))
        return ans