Leetcode - max-area-of-island
https://leetcode.com/problems/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.)
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.
# @param {Integer[][]} grid
# @return {Integer}
def max_area_of_island(grid)
return 0 if grid.length == 0 || grid[0].length == 0
max_count = 0
for i in 0..grid.length-1
for j in 0..grid[0].length-1
if grid[i][j] == 1
curr_count = walk(grid, i, j)
max_count = curr_count > max_count ? curr_count : max_count
end
end
end
return max_count
end
def walk(grid, i, j)
if i < 0 || j < 0 || i >= grid.length || j >= grid[0].length
return 0
end
if grid[i][j] == 1
count = 1
grid[i][j] = 2
count += walk(grid, i, j+1)
count += walk(grid, i, j-1)
count += walk(grid, i+1, j)
count += walk(grid, i-1, j)
return count
end
return 0
end
评论 (0)