LeetCode Max Area of Island Solution Explained - Java

preview_player
Показать описание


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

instead of that extra seen boolean, before the return statement in the area function just write grid[r][c] = 0.

_ParijatChatterjee
Автор

Here's an optimized version in JavaScript, instead of having the seen global variable, we can simply set the 1s equal to 0 once we've viewed them. Got the idea from Nick's video on 'Number of Islands' leetcode problem:

/**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function(grid) {
let maxArea = 0;

for(let i = 0; i < grid.length; i++) {
for(let j = 0; j < grid[0].length;j++) {
if(grid[i][j] === 1) {
let areaOfIsland = dfs(grid, i, j);
if(areaOfIsland > maxArea) {
maxArea = areaOfIsland;
}
}
}
}

return maxArea;
};

const dfs = (matrix, i, j, area) => {
if(i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length || matrix[i][j] === 0) {
return 0;
}
if(!area) area = 1;
area += 1;
matrix[i][j] = 0;

let up = dfs(matrix, i - 1, j, area);
let down = dfs(matrix, i + 1, j, area);
let left = dfs(matrix, i, j - 1, area);
let right = dfs(matrix, i, j + 1, area);

return 1 + up + down + right + left;
}

juanvibeats
Автор

Hey Nick, did you study any other questions too for your tech interviews. If you can share complete list you solved before interview that would be great!

vikrant
Автор

could u pls upload word ladder 2 problem

lifehacks
Автор

Can you explain why you are returning 1 + the recursive call?

joecamroberon
Автор

It is not working in the test case of

[[0], [1]]. Please explain it. Thanks

vishaldhanani
Автор

Just to check if I'm understanding, we should return 0 on a seen island because, if we don't and we keep recursively visiting that island our area for the max area would go to infinity because it keeps checking its neighbor and its neighbor keeps checking it.

ZEEEDgenx
Автор

"Time Limit Exceeded", time-complexity is too high.

msantagiulianab