-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
695. Max Area of Island #121
Comments
Solution 1 ( DFS )
/**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function(grid) {
const mark = Array.from(new Array(grid.length), () => new Array(grid[0].length).fill(0));
let result = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] === 1 && mark[i][j] === 0) {
result = Math.max(result, dfs(i, j));
}
}
}
return result;
function dfs(i, j) {
let area = 0;
const direction = [-1, 0, 1, 0, -1];
const stack = [[i, j]];
mark[i][j] = 1;
while (stack.length !== 0) {
const [x, y] = stack.pop();
area++;
for (let d = 0; d < 4; d++) {
const dx = direction[d] + x;
const dy = direction[d + 1] + y;
if (
dx >= 0
&& dx < grid.length
&& dy >= 0
&& dy < grid[0].length
&& grid[dx][dy] === 1
&& mark[dx][dy] === 0
) {
mark[dx][dy] = 1;
stack.push([dx, dy]);
}
}
}
return area;
}
}; Solution 2 ( BFS )
/**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function(grid) {
const mark = Array.from(new Array(grid.length), () => new Array(grid[0].length).fill(0));
let result = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] === 1 && mark[i][j] === 0) {
result = Math.max(result, bfs(i, j));
}
}
}
return result;
function bfs(i, j) {
let area = 0;
const direction = [-1, 0, 1, 0, -1];
const queue = [[i, j]];
mark[i][j] = 1;
while (queue.length !== 0) {
const [x, y] = queue.shift();
area++;
for (let d = 0; d < 4; d++) {
const dx = direction[d] + x;
const dy = direction[d + 1] + y;
if (
dx >= 0
&& dx < grid.length
&& dy >= 0
&& dy < grid[0].length
&& grid[dx][dy] === 1
&& mark[dx][dy] === 0
) {
mark[dx][dy] = 1;
queue.push([dx, dy]);
}
}
}
return area;
}
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
695. Max Area of Island
Given a non-empty 2D array
grid
of 0's and 1's, an island is a group of1
'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
Given the above grid, return
6
. Note the answer is not 11, because the island must be connected 4-directionally.Example 2
Given the above grid, return
0
.Note
The text was updated successfully, but these errors were encountered: