This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

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,Given the above grid, return1,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]]

`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.

b'

\n#### Approach #1: Depth-First Search (Recursive) [Accepted]

\n

\n#### Approach #2: Depth-First Search (Iterative) [Accepted]

\n

\n

'
\n\n

\n**Intuition and Algorithm**

We want to know the area of each connected shape in the grid, then take the maximum of these.

\nIf we are on a land square and explore every square connected to it 4-directionally (and recursively squares connected to those squares, and so on), then the total number of squares explored will be the area of that connected shape.

\nTo ensure we don\'t count squares in a shape more than once, let\'s use `seen`

to keep track of squares we haven\'t visited before. It will also prevent us from counting the same shape more than once.

**Complexity Analysis**

- \n
- \n
Time Complexity: , where is the number of rows in the given

\n`grid`

, and is the number of columns. We visit every square once. \n - \n
Space complexity: , the space used by

\n`seen`

to keep track of visited squares, and the space used by the call stack during our recursion. \n

\n

**Intuition and Algorithm**

We can try the same approach using a stack based, (or "iterative") depth-first search.

\nHere, `seen`

will represent squares that have either been visited or are added to our list of squares to visit (`stack`

). For every starting land square that hasn\'t been visited, we will explore 4-directionally around it, adding land squares that haven\'t been added to `seen`

to our `stack`

.

On the side, we\'ll keep a count `shape`

of the total number of squares seen during the exploration of this shape. We\'ll want the running max of these counts.

**Complexity Analysis**

- \n
- \n
Time Complexity: , where is the number of rows in the given

\n`grid`

, and is the number of columns. We visit every square once. \n - \n
Space complexity: , the space used by

\n`seen`

to keep track of visited squares, and the space used by`stack`

. \n

\n

Analysis written by: @awice

\n