Skip to content

Crack SDE

Most of the content are generated by AI, with human being reviewed, edited, and revised

Menu
  • Home
  • Daily English Story
  • Tech Interviews
  • Cloud Native
  • DevOps
  • Artificial Intelligence
Menu

LC#695. Max Area of Island

Posted on 02/16/202502/16/2025 by user

Leetcode 695. Max Area of Island is an extension of the island problem where we need to find the largest island in a grid of 1s (land) and 0s (water).


Problem Statement

Given an m x n binary grid, find the maximum area of an island. An island is a group of 1s connected 4-directionally (up, down, left, right). You may assume all four edges of the grid are surrounded by 0.


Approach

We can solve this using DFS (Depth-First Search) or BFS (Breadth-First Search):

  1. Use DFS (or BFS) to explore the entire island when we find a 1.
  2. Mark visited cells as 0 to avoid counting them multiple times.
  3. Track the maximum size encountered.

Golang Solution (DFS)

package main

import (
	"fmt"
)

// Directions for 4-way connectivity
var directions = [][]int{
	{1, 0}, {-1, 0}, {0, 1}, {0, -1},
}

// DFS function to compute island size
func dfs(grid [][]int, r, c int) int {
	// Boundary conditions and if already visited or water
	if r < 0 || r >= len(grid) || c < 0 || c >= len(grid[0]) || grid[r][c] == 0 {
		return 0
	}

	// Mark cell as visited
	grid[r][c] = 0
	size := 1

	// Explore all 4 directions
	for _, dir := range directions {
		size += dfs(grid, r+dir[0], c+dir[1])
	}

	return size
}

// Function to find max area of an island
func maxAreaOfIsland(grid [][]int) int {
	maxSize := 0

	for r := 0; r < len(grid); r++ {
		for c := 0; c < len(grid[0]); c++ {
			if grid[r][c] == 1 {
				// Start DFS and update maxSize
				size := dfs(grid, r, c)
				if size > maxSize {
					maxSize = size
				}
			}
		}
	}

	return maxSize
}

// Main function to test
func main() {
	grid := [][]int{
		{0, 0, 1, 0, 0},
		{1, 1, 1, 0, 0},
		{0, 1, 0, 0, 1},
		{0, 0, 0, 1, 1},
	}

	fmt.Println("Max Area of Island:", maxAreaOfIsland(grid)) // Output: 5
}

Alternative Approach: BFS

Instead of DFS recursion, we can use BFS (queue-based traversal):

package main

import (
	"fmt"
	"container/list"
)

// BFS function to compute island size
func bfs(grid [][]int, r, c int) int {
	queue := list.New()
	queue.PushBack([]int{r, c})
	grid[r][c] = 0
	size := 0

	directions := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}

	for queue.Len() > 0 {
		cell := queue.Remove(queue.Front()).([]int)
		x, y := cell[0], cell[1]
		size++

		for _, dir := range directions {
			nx, ny := x+dir[0], y+dir[1]
			if nx >= 0 && nx < len(grid) && ny >= 0 && ny < len(grid[0]) && grid[nx][ny] == 1 {
				grid[nx][ny] = 0
				queue.PushBack([]int{nx, ny})
			}
		}
	}

	return size
}

// Function to find max area of an island
func maxAreaOfIslandBFS(grid [][]int) int {
	maxSize := 0

	for r := 0; r < len(grid); r++ {
		for c := 0; c < len(grid[0]); c++ {
			if grid[r][c] == 1 {
				// Start BFS and update maxSize
				size := bfs(grid, r, c)
				if size > maxSize {
					maxSize = size
				}
			}
		}
	}

	return maxSize
}

// Main function to test BFS
func main() {
	grid := [][]int{
		{0, 0, 1, 0, 0},
		{1, 1, 1, 0, 0},
		{0, 1, 0, 0, 1},
		{0, 0, 0, 1, 1},
	}

	fmt.Println("Max Area of Island (BFS):", maxAreaOfIslandBFS(grid)) // Output: 5
}

Complexity Analysis

Both DFS and BFS approaches have similar complexity:

  • Time Complexity: O(m * n), where m is the number of rows and n is the number of columns. Each cell is visited once.
  • Space Complexity:
    • DFS: O(m * n) in the worst case (recursion stack).
    • BFS: O(min(m, n)) for the queue.

Enhancements & Harder Versions

1️⃣ Include Diagonal Connectivity

Modify the directions array to include diagonal moves:

var directions = [][]int{
	{1, 0}, {-1, 0}, {0, 1}, {0, -1},
	{1, 1}, {1, -1}, {-1, 1}, {-1, -1}, // Diagonal moves
}

2️⃣ Find All Island Sizes (Instead of Just Max)

Modify the function to return all island sizes instead of just the max:

func allIslandSizes(grid [][]int) []int {
	var sizes []int
	for r := 0; r < len(grid); r++ {
		for c := 0; c < len(grid[0]); c++ {
			if grid[r][c] == 1 {
				sizes = append(sizes, dfs(grid, r, c))
			}
		}
	}
	return sizes
}

3️⃣ Ignore Islands Below a Size Threshold

Ignore islands smaller than k:

func maxAreaAboveThreshold(grid [][]int, k int) int {
	maxSize := 0
	for r := 0; r < len(grid); r++ {
		for c := 0; c < len(grid[0]); c++ {
			if grid[r][c] == 1 {
				size := dfs(grid, r, c)
				if size >= k && size > maxSize {
					maxSize = size
				}
			}
		}
	}
	return maxSize
}

Final Thoughts

  • DFS is easier to implement but can hit stack overflow for large grids.
  • BFS avoids recursion depth issues and is preferred for large-scale problems.
  • Enhancements like diagonal connections and minimum-size thresholds make the problem more complex.

🔥 This Golang solution is efficient, modular, and ready for harder variations of the island problem! 🚀

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related

Recent Posts

  • LC#622 Design Circular Queue
  • Started with OpenTelemetry in Go
  • How Prometheus scrap works, and how to find the target node and get the metrics files
  • How to collect metrics of container, pods, node and cluster in k8s?
  • LC#200 island problem

Recent Comments

  1. another user on A Journey of Resilience

Archives

  • May 2025
  • April 2025
  • February 2025
  • July 2024
  • April 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023

Categories

  • Artificial Intelligence
  • Cloud Computing
  • Cloud Native
  • Daily English Story
  • Database
  • DevOps
  • Golang
  • Java
  • Leetcode
  • Startups
  • Tech Interviews
©2025 Crack SDE | Design: Newspaperly WordPress Theme
Manage Cookie Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
View preferences
{title} {title} {title}