Skip to content

2problems completed#1392

Open
BharathVuppala96 wants to merge 1 commit intosuper30admin:masterfrom
BharathVuppala96:master
Open

2problems completed#1392
BharathVuppala96 wants to merge 1 commit intosuper30admin:masterfrom
BharathVuppala96:master

Conversation

@BharathVuppala96
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

Strengths:

  • You have correctly identified the BFS approach for flood fill.
  • You correctly handle the base case where the starting pixel already has the new color.
  • You use the directions list to check neighbors, which is a good practice.

Areas for Improvement:

  • Queue Management: Instead of appending row and column as separate elements and popping two at a time, you should append them as a pair (e.g., a list or tuple). This avoids confusion and makes the code more robust. For example, use queue.append([sr, sc]) and then pop the entire pair at once: curr = queue.pop(0) and then use curr[0] and curr[1] for row and column.
  • Efficiency: Use collections.deque for efficient popping from the left. Using list.pop(0) is inefficient for large lists because it requires shifting all elements. Instead, import deque and use queue = deque() and queue.popleft().
  • Code Clarity: The variable names are adequate, but consider using more descriptive names like row and col instead of cr and cc. Also, the directions list is good, but you can name it directions for clarity.
  • Boundary Checks: Your boundary checks are correct, but ensure that you are consistent. In the BFS, you check nr>=0 and nc>=0 and nr<len(image) and nc<len(image[0]), which is correct.

Revised Code Suggestion:

from collections import deque

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        old_color = image[sr][sc]
        if old_color == color:
            return image
        directions = [[-1,0], [0,1], [1,0], [0,-1]]
        queue = deque()
        queue.append([sr, sc])
        image[sr][sc] = color
        
        while queue:
            curr = queue.popleft()
            r, c = curr[0], curr[1]
            for dir in directions:
                nr = r + dir[0]
                nc = c + dir[1]
                if nr >= 0 and nc >= 0 and nr < len(image) and nc < len(image[0]) and image[nr][nc] == old_color:
                    image[nr][nc] = color
                    queue.append([nr, nc])
        return image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants