zoukankan      html  css  js  c++  java
  • 695. Max Area of Island

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

    给一个二维数组,0表示空,1表示岛,上下左右如果有1相邻,那么属于同一个岛,问1最多的岛的1个个数是多少。

    就是求最大联通快1的个数。dfs或者bfs都可以。

    class Solution(object):
        def maxAreaOfIsland(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            n = len(grid)
            m = len(grid[0])
            vis = []
            for i in range(n):
                vis.append([0] * m)
            def dfs(grid, vis, i, j, n, m):
                dires = [[0, 1], [0, -1], [1, 0], [-1, 0]]
                vis[i][j] = 1
                ans = 1
                for dire in dires:
                    x = i + dire[0]
                    y = j + dire[1]
                    if x < n and x >= 0 and y < m and y >= 0 and grid[x][y] == 1 and vis[x][y] == 0:
                        ans += dfs(grid, vis, x, y, n, m)
                return ans
                
            ans = 0
            for i in range(n):
                for j in range(m):
                    if vis[i][j] == 0 and grid[i][j] == 1:
                        ans = max(ans, dfs(grid, vis, i, j, n, m))
            return ans
  • 相关阅读:
    Java程序性能优化——让你的java程序更快、更稳定
    synchronized和ReentrantLock
    Java集合——ConcurrentHashMap
    SpringMVC流程
    计算机网络http,https,tcp,udp,get,post
    JVM类加载机制
    关于strcpy和memcpy
    C语言指针
    malloc函数详解
    进程和线程
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13360128.html
Copyright © 2011-2022 走看看