← Home

695. Max Area of Island

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
graph traversalC++Markdown
695

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 695. Max Area of Island, the solution in this repository is mainly a graph traversal solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: graph traversal, stack.

The notes already sitting in the source point us in the right direction:

  • Approach #1: Depth-First Search (Recursive) [Accepted]
  • time: O(R*C), space: O(R*C)

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are area, maxAreaOfIsland.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(R*C), space: O(R*C)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Approach #1: Depth-First Search (Recursive) [Accepted]
02//Runtime: 32 ms, faster than 17.35% of C++ online submissions for Max Area of Island.
03//Memory Usage: 11.4 MB, less than 66.67% of C++ online submissions for Max Area of Island.
04//time: O(R*C), space: O(R*C)
05class Solution {
06public:
07    int m, n;
08    vector<vector<bool>> visited;
09    
10    int area(vector<vector<int>>& grid, int r, int c){
11        //return 0 for visited cell because we have already calculated the area of the island containing this cell
12        if(r < 0 || r >= m || c < 0 || c >= n || visited[r][c] || grid[r][c] == 0) return 0;
13        
14        visited[r][c] = true;
15        
16        return 1 + area(grid, r+1, c) + area(grid, r-1, c) + area(grid, r, c+1) + area(grid, r, c-1);
17    };
18    
19    int maxAreaOfIsland(vector<vector<int>>& grid) {
20        m = grid.size(), n = grid[0].size();
21        visited = vector<vector<bool>>(m, vector<bool>(n, false));
22        int ans = 0;
23        for(int i = 0; i < m; i++){
24            for(int j = 0; j < n; j++){
25                ans = max(ans, area(grid, i, j));
26            }
27        }
28        
29        return ans;
30    }
31};
32
33//Approach #2: Depth-First Search (Iterative) [Accepted]
34//Runtime: 32 ms, faster than 17.35% of C++ online submissions for Max Area of Island.
35//Memory Usage: 16 MB, less than 19.05% of C++ online submissions for Max Area of Island.
36//time: O(R*C), space: O(R*C)
37class Solution {
38public:
39    int maxAreaOfIsland(vector<vector<int>>& grid) {
40        int m = grid.size(), n = grid[0].size();
41        vector<vector<bool>> visited = vector<vector<bool>>(m, vector<bool>(n, false));
42        vector<int> dr = {1, -1, 0, 0};
43        vector<int> dc = {0, 0, 1, -1};
44        
45        int ans = 0;
46        
47        for(int r0 = 0; r0 < m; r0++){
48            for(int c0 = 0; c0 < n; c0++){
49                if(grid[r0][c0] && !visited[r0][c0]){
50                    int area = 0;
51                    stack<vector<int>> stk;
52                    stk.push({r0, c0});
53//MODE1 and MODE2 work the same, just the places of "visited[r0][c0] = true;" are different
54#ifdef MODE1
55                    visited[r0][c0] = true;
56#endif
57                    //dfs for a cell, find the area
58                    while(!stk.empty()){
59                        vector<int> node = stk.top(); stk.pop();
60                        int r = node[0], c = node[1];
61                        area++;
62#ifdef MODE2
63                        if(!visited[r][c]){
64                            area++;
65                            visited[r][c] = true;
66                        }
67#endif
68                        for(int k = 0; k < 4; k++){
69                            int nr = r + dr[k];
70                            int nc = c + dc[k];
71                            if(nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] && !visited[nr][nc])
72                            {
73                                stk.push({nr, nc});
74#ifdef MODE1
75                                visited[nr][nc] = true;
76#endif
77                            }
78                        }
79                    }
80                    ans = max(ans, area);
81                }
82            }
83        }
84        
85        return ans;
86    }
87};

Cost

Complexity

Time
O(R*C), space: O(R*C)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.