Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 1162 · Multi-Source BFS

As Far from Land as Possible

LeetCode 1162 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Multi-source BFS from land; answer = last distance.

ಮಧ್ಯಮArrayDynamic ProgrammingBreadth-First SearchMatrix
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು As Far from Land as Possible (LeetCode 1162) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Multi-Source BFS ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Start a BFS from every land cell at once. The water cell reached last is the one farthest from any land, and its BFS distance is the answer.

Approach

  1. 1

    Queue every land cell (distance 0).

  2. 2

    All land or all water → −1.

  3. 3

    BFS outward, tracking the largest distance popped.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Multi-source BFSPythonO(n²) time
class Solution:
    def maxDistance(self, grid: list[list[int]]) -> int:
        q = deque([])
        max_distance = -1
        m = len(grid)
        n = len(grid[0])
        visited = set()
        for i in range(m):
            for j in range(n):
                if grid[i][j]==1:
                    q.append((i,j,0))
                    visited.add((i,j))
        if len(q) == 0 or len(q) == m * n: #if all land or all water
            return -1
        di =[0,+1,0,-1]
        dj=[+1,0,-1,0]
        while q:
            x0,y0,dist = q.popleft()
            max_distance=max(max_distance,dist)
            for k in range(4):
                x1 = x0+di[k]
                y1 = y0+dj[k]
                if 0<=x1<m and 0<=y1<n and (x1,y1) not in visited:
                    visited.add((x1,y1))
                    q.append((x1,y1,dist+1))
        return max_distance





ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

As Far from Land as Possible — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

As Far from Land as Possible ಹಿಂದಿನ intuition ಏನು?

Start a BFS from every land cell at once. The water cell reached last is the one farthest from any land, and its BFS distance is the answer.

As Far from Land as Possible (LeetCode 1162) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Queue every land cell (distance 0). 2. All land or all water → −1. 3. BFS outward, tracking the largest distance popped.

As Far from Land as Possible ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n²). Space: O(n²). (Accepted approach: Multi-source BFS.)

As Far from Land as Possible ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Manhattan distance on a grid equals BFS steps.