LeetCode 1162: As Far from Land as Possible Solution

Master LeetCode problem 1162 (As Far from Land as Possible), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1162. As Far from Land as Possible

Problem Explanation

Explanation:

  • Algorithmic Idea:

    1. We start by iterating over the grid to find all land cells and add them to a queue.
    2. Then we perform a BFS from each land cell to find the maximum distance to a water cell.
    3. We keep track of the maximum distance found during the BFS.
    4. Finally, we return the maximum distance as the result.
  • Time Complexity: O(n^2) where n is the size of the grid.

  • Space Complexity: O(n^2) for storing the queue and distances.

:

Solution Code

class Solution {
    public int maxDistance(int[][] grid) {
        int n = grid.length;
        Queue<int[]> queue = new LinkedList<>();
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    queue.offer(new int[]{i, j});
                }
            }
        }
        
        int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        int maxDistance = -1;
        
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            for (int[] dir : directions) {
                int x = cell[0] + dir[0];
                int y = cell[1] + dir[1];
                if (x >= 0 && x < n && y >= 0 && y < n && grid[x][y] == 0) {
                    grid[x][y] = grid[cell[0]][cell[1]] + 1;
                    maxDistance = Math.max(maxDistance, grid[x][y] - 1);
                    queue.offer(new int[]{x, y});
                }
            }
        }
        
        return maxDistance;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1162 (As Far from Land as Possible)?

This page provides optimized solutions for LeetCode problem 1162 (As Far from Land as Possible) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1162 (As Far from Land as Possible)?

The time complexity for LeetCode 1162 (As Far from Land as Possible) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1162 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1162 in Java, C++, or Python.

Back to LeetCode Solutions