Problem
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.)
Example 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]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
class Solution { public int maxAreaOfIsland(int[][] grid) { int max = 0; if (grid == null || grid.length == 0 || grid[0].length == 0) return max; 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(max, dfs(grid, i, j)); } } return max; } private int dfs(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+dfs(grid, i-1, j)+dfs(grid, i+1, j)+dfs(grid, i, j-1)+dfs(grid, i, j+1); } return 0; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/72223.html
摘要:返回注意答案并不是因?yàn)殛懙叵噙B要求必須是在上下左右四個(gè)方向。返回應(yīng)為想法我們還是要遍歷數(shù)組中的每一個(gè)元素。如果數(shù)組元素值為,則我們以這個(gè)值為起點(diǎn)進(jìn)行深度優(yōu)先搜索。 題目詳情 Given a non-empty 2D array grid of 0s and 1s, an island is a group of 1s (representing land) connected 4-di...
摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的。可能大家看著也非常不方便。所以在這里做個(gè)索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的。可能大家看著也非常不方便。所以在這里做個(gè)索引嘻嘻。 順序整理 1~50 1...
摘要:找到給定的二維數(shù)組中最大的島嶼面積。思路給定一個(gè)由和組成的二維數(shù)組,其中代表島嶼土地,要求找出二維數(shù)組中最大的島嶼面積,沒有則返回。樣例如樣例所示,二維數(shù)組的最大島嶼面積為,下面來講解深度優(yōu)先搜索的做法。 ...
Problem You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is com...
摘要:要求計(jì)算出島嶼的周長(zhǎng)。思路和代碼這題不難,直觀的來看,其實(shí)只要判斷出這一塊土地幾面臨海就知道需要加上幾條邊長(zhǎng)。臨海的判斷有兩個(gè),一個(gè)是這塊地位于數(shù)組的邊緣,一個(gè)是這塊地相鄰的元素為,即海洋。代碼如下上方臨海左側(cè)臨海右側(cè)臨海下方臨海 題目要求 You are given a map in form of a two-dimensional integer grid where 1 rep...
閱讀 2397·2021-10-09 09:44
閱讀 2132·2021-10-08 10:05
閱讀 3424·2021-07-26 23:38
閱讀 2991·2019-08-28 18:16
閱讀 812·2019-08-26 11:55
閱讀 1821·2019-08-23 18:29
閱讀 2035·2019-08-23 18:05
閱讀 1364·2019-08-23 17:02