#827
Hard Algorithms Making a large island
Array Depth-First Search Breadth-First Search Union-Find Matrix
56.3% acceptance
Feb 22, 2026
5010
99
You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Solution
Rust
Time O(n³)
Space O(n)
/*
* You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
* Return the size of the largest island in grid after applying this operation.
* An island is a 4-directionally connected group of 1s.
* Example 1:
* Input: grid = [[1,0],[0,1]]
* Output: 3
* Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
* Example 2:
* Input: grid = [[1,1],[1,0]]
* Output: 4
* Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.
* Example 3:
* Input: grid = [[1,1],[1,1]]
* Output: 4
* Explanation: Can't change any 0 to 1, only one island with area = 4.
* Constraints:
* n == grid.length
* n == grid[i].length
* 1 <= n <= 500
* grid[i][j] is either 0 or 1.
*/
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn largest_island(mut grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
let mut id = 2i32;
let mut size: HashMap<i32, i32> = HashMap::new();
fn dfs(grid: &mut Vec<Vec<i32>>, r: usize, c: usize, id: i32, size: &mut i32) {
let n = grid.len();
if grid[r][c] != 1 { return; }
grid[r][c] = id;
*size += 1;
if r > 0 { dfs(grid, r-1, c, id, size); }
if c > 0 { dfs(grid, r, c-1, id, size); }
if r+1 < n { dfs(grid, r+1, c, id, size); }
if c+1 < n { dfs(grid, r, c+1, id, size); }
}
for i in 0..n {
for j in 0..n {
if grid[i][j] == 1 {
let mut s = 0;
dfs(&mut grid, i, j, id, &mut s);
size.insert(id, s);
id += 1;
}
}
}
let mut ans = *size.values().max().unwrap_or(&0);
let dirs: [(i32,i32);4] = [(-1,0),(1,0),(0,-1),(0,1)];
for i in 0..n {
for j in 0..n {
if grid[i][j] == 0 {
let mut seen: HashSet<i32> = HashSet::new();
let mut total = 1;
for &(dr, dc) in &dirs {
let nr = i as i32 + dr;
let nc = j as i32 + dc;
if nr >= 0 && nc >= 0 && nr < n as i32 && nc < n as i32 {
let cid = grid[nr as usize][nc as usize];
if cid > 1 && seen.insert(cid) {
total += size[&cid];
}
}
}
ans = ans.max(total);
}
}
}
ans
}
}