🧠
Alternative Approach: BFS with Distance Matrix
💡 This approach explicitly maintains a distance matrix to track the shortest distance from land to each water cell, reinforcing BFS layer concepts.
Intuition
Initialize distances for land cells as 0 and water cells as -1. BFS updates distances for neighbors, ensuring shortest distance propagation.
Algorithm
- Create a distance matrix initialized with -1 for water and 0 for land.
- Enqueue all land cells.
- Perform BFS, updating distance for each water neighbor as current cell distance + 1.
- Return the maximum distance found in the distance matrix.
💡 This approach makes distance updates explicit, helping beginners visualize BFS progression.
from collections import deque
from typing import List
def maxDistance(grid: List[List[int]]) -> int:
n = len(grid)
dist = [[-1]*n for _ in range(n)]
queue = deque()
for r in range(n):
for c in range(n):
if grid[r][c] == 1:
dist[r][c] = 0
queue.append((r, c))
if len(queue) == 0 or len(queue) == n * n:
return -1
directions = [(1,0), (-1,0), (0,1), (0,-1)]
max_dist = -1
while queue:
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
max_dist = max(max_dist, dist[nr][nc])
queue.append((nr, nc))
return max_dist
# Driver code
if __name__ == '__main__':
grid = [[1,0,1],[0,0,0],[1,0,1]]
print(maxDistance(grid)) # Expected output: 2
Line Notes
dist = [[-1]*n for _ in range(n)]Initialize distance matrix with -1 for unvisited water cells
if grid[r][c] == 1:Set distance 0 for land cells and enqueue them
if len(queue) == 0 or len(queue) == n * n:Handle edge cases with no water or no land
while queue:Process BFS until all reachable water cells are visited
if dist[nr][nc] == -1:Only update distance for unvisited water cells
dist[nr][nc] = dist[r][c] + 1Update distance as one more than current cell
max_dist = max(max_dist, dist[nr][nc])Track maximum distance found
import java.util.*;
public class Solution {
public static int maxDistance(int[][] grid) {
int n = grid.length;
int[][] dist = new int[n][n];
for (int[] row : dist) Arrays.fill(row, -1);
Queue<int[]> queue = new LinkedList<>();
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
if (grid[r][c] == 1) {
dist[r][c] = 0;
queue.offer(new int[]{r, c});
}
}
}
if (queue.isEmpty() || queue.size() == n * n) return -1;
int[][] directions = {{1,0}, {-1,0}, {0,1}, {0,-1}};
int maxDist = -1;
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int r = cell[0], c = cell[1];
for (int[] d : directions) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < n && nc >= 0 && nc < n && dist[nr][nc] == -1) {
dist[nr][nc] = dist[r][c] + 1;
maxDist = Math.max(maxDist, dist[nr][nc]);
queue.offer(new int[]{nr, nc});
}
}
}
return maxDist;
}
public static void main(String[] args) {
int[][] grid = {{1,0,1},{0,0,0},{1,0,1}};
System.out.println(maxDistance(grid)); // Expected output: 2
}
}
Line Notes
int[][] dist = new int[n][n];Distance matrix initialized to -1 for water cells
if (grid[r][c] == 1) {Set distance 0 for land cells and enqueue
if (queue.isEmpty() || queue.size() == n * n) return -1;Handle edge cases
while (!queue.isEmpty()) {BFS traversal to update distances
if (dist[nr][nc] == -1) {Update only unvisited water cells
dist[nr][nc] = dist[r][c] + 1;Distance is one more than current cell
maxDist = Math.max(maxDist, dist[nr][nc]);Track maximum distance
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int maxDistance(vector<vector<int>>& grid) {
int n = grid.size();
vector<vector<int>> dist(n, vector<int>(n, -1));
queue<pair<int,int>> q;
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
if (grid[r][c] == 1) {
dist[r][c] = 0;
q.push({r, c});
}
}
}
if (q.empty() || q.size() == n * n) return -1;
int directions[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};
int maxDist = -1;
while (!q.empty()) {
auto [r, c] = q.front(); q.pop();
for (auto& d : directions) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < n && nc >= 0 && nc < n && dist[nr][nc] == -1) {
dist[nr][nc] = dist[r][c] + 1;
maxDist = max(maxDist, dist[nr][nc]);
q.push({nr, nc});
}
}
}
return maxDist;
}
int main() {
vector<vector<int>> grid = {{1,0,1},{0,0,0},{1,0,1}};
cout << maxDistance(grid) << endl; // Expected output: 2
return 0;
}
Line Notes
vector<vector<int>> dist(n, vector<int>(n, -1));Initialize distance matrix with -1 for water
if (grid[r][c] == 1) {Set distance 0 for land and enqueue
if (q.empty() || q.size() == n * n) return -1;Handle edge cases
while (!q.empty()) {BFS traversal to update distances
if (dist[nr][nc] == -1) {Update only unvisited water cells
dist[nr][nc] = dist[r][c] + 1;Distance is one more than current cell
maxDist = max(maxDist, dist[nr][nc]);Track maximum distance
function maxDistance(grid) {
const n = grid.length;
const dist = Array.from({length: n}, () => Array(n).fill(-1));
const queue = [];
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
if (grid[r][c] === 1) {
dist[r][c] = 0;
queue.push([r, c]);
}
}
}
if (queue.length === 0 || queue.length === n * n) return -1;
const directions = [[1,0], [-1,0], [0,1], [0,-1]];
let maxDist = -1;
while (queue.length > 0) {
const [r, c] = queue.shift();
for (const [dr, dc] of directions) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < n && nc >= 0 && nc < n && dist[nr][nc] === -1) {
dist[nr][nc] = dist[r][c] + 1;
maxDist = Math.max(maxDist, dist[nr][nc]);
queue.push([nr, nc]);
}
}
}
return maxDist;
}
// Test
console.log(maxDistance([[1,0,1],[0,0,0],[1,0,1]])); // Expected output: 2
Line Notes
const dist = Array.from({length: n}, () => Array(n).fill(-1));Initialize distance matrix with -1 for water
if (grid[r][c] === 1) {Set distance 0 for land and enqueue
if (queue.length === 0 || queue.length === n * n) return -1;Handle edge cases
while (queue.length > 0) {BFS traversal to update distances
if (dist[nr][nc] === -1) {Update only unvisited water cells
dist[nr][nc] = dist[r][c] + 1;Distance is one more than current cell
maxDist = Math.max(maxDist, dist[nr][nc]);Track maximum distance
Each cell is visited once in BFS, so time is O(n^2). Space is O(n^2) for distance matrix and queue.
💡 This approach is similar to the previous BFS but makes distance tracking explicit, which can help beginners understand BFS layers.
Interview Verdict: Accepted
This approach is also optimal and accepted, useful for clarity and teaching BFS distance propagation.